I got this after adding Episerver Find to our site and installing the corresponding NuGet package for Episerver Find.
The fix was easy: update all Episerver related add-ons as well (even if they seem unrelated: CMS, CMS.TinyMCE, CMS.UI, etc.)
After updating all possible Episerver add-ons and recompiling, the error went away.
I did an upgraded version of jezzipin's answer (and I'm animating padding top instead of height but you still get the point.
/**
* ResizeHeaderOnScroll
*
* @constructor
*/
var ResizeHeaderOnScroll = function()
{
this.protocol = window.location.protocol;
this.domain = window.location.host;
};
ResizeHeaderOnScroll.prototype.init = function()
{
if($(document).scrollTop() > 0)
{
$('header').data('size','big');
} else {
$('header').data('size','small');
}
ResizeHeaderOnScroll.prototype.checkScrolling();
$(window).scroll(function(){
ResizeHeaderOnScroll.prototype.checkScrolling();
});
};
ResizeHeaderOnScroll.prototype.checkScrolling = function()
{
if($(document).scrollTop() > 0)
{
if($('header').data('size') == 'big')
{
$('header').data('size','small');
$('header').stop().animate({
paddingTop:'1em',
paddingBottom:'1em'
},200);
}
}
else
{
if($('header').data('size') == 'small')
{
$('header').data('size','big');
$('header').stop().animate({
paddingTop:'3em'
},200);
}
}
}
$(document).ready(function(){
var resizeHeaderOnScroll = new ResizeHeaderOnScroll();
resizeHeaderOnScroll.init()
})
Most of the answers given above are for React.Component based designs. If your are using useState
in the recent upgrades of React library, then follow this answer
Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer
The easiest way to see benefits from this is to look at this example.
Every MVC framework has a Router/Dispatcher
that maps URL-s to actionControllers.
So URL like this: /blog/article/1
would invoke blogController::articleAction($id);
Now this Router is only aware of the URL or /blog/article/1/
But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.
That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.
For example:
if you want to retrive article 1 you can do this:
GET /blog/article/1 HTTP/1.1
but if you want to delete article 1 you will do this:
DELETE /blog/article/1 HTTP/1.1
Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.
Read this two articles, they might help you:
These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.
Hope this helps!
i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer
will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}
String source = "testString";
byte[] byteArray = source.getBytes(encoding);
You can foreach and do the same with all the strings in the array.
string userName;
string userId;
if (HttpContext.Current != null && HttpContext.Current.User != null
&& HttpContext.Current.User.Identity.Name != null)
{
userName = HttpContext.Current.User.Identity.Name;
userId = HttpContext.Current.User.Identity.GetUserId();
}
Or based on Darrel Miller's comment, maybe use this to retrieve the HttpContext first.
// get httpContext
object httpContext;
actionContext.Request.Properties.TryGetValue("MS_HttpContext", out httpContext);
See also:
In Bootstrap 3+ the most appropriate way to change the size of a modal dialog is to use the size property. Below is an example, notice the modal-sm
along the modal-dialog
class, indicating a small modal. It can contain the values sm
for small, md
for medium and lg
for large.
<div class="modal fade" id="ww_vergeten" tabindex="-1" role="dialog" aria-labelledby="modal_title" aria-hidden="true">
<div class="modal-dialog modal-sm"> <!-- property to determine size -->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="modal_title">Some modal</h4>
</div>
<div class="modal-body">
<!-- modal content -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="some_button" data-loading-text="Loading...">Send</button>
</div>
</div>
</div>
</div>
Thought of writing this answer as nothing worked from above & you don't want to specify proxy location.
If you're using httpClient
then consider this.
HttpClientHandler handler = new HttpClientHandler();
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
handler.Proxy = proxy;
var client = new HttpClient(handler);
// your next steps...
And if you're using HttpWebRequest
:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri + _endpoint);
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;
Kind referencce: https://medium.com/@siriphonnot/the-remote-server-returned-an-error-407-proxy-authentication-required-86ae489e401b
I don't know if it helps, but using jQuery, to hide an email address, I did :
$(function() {
// planque l'adresse mail
var mailSplitted
= ['mai', 'to:mye', 'mail@', 'addre', 'ss.fr'];
var link = mailSplitted.join('');
link = '<a href="' + link + '"</a>';
$('mytag').wrap(link);
});
I hope it helps.
BTW, Yandex Metrica also uses IDFA.
./Pods/YandexMobileMetrica/libYandexMobileMetrica.a
They say on their GitHub page that
"Starting from version 1.6.0 Yandex AppMetrica became also a tracking instrument and uses Apple idfa to attribute installs. Because of that during submitting your application to the AppStore you will be prompted with three checkboxes to state your intentions for idfa usage. As Yandex AppMetrica uses idfa for attributing app installations you need to select Attribute this app installation to a previously served advertisement."
So, I will try to select this checkbox and send my app without actually no any ads in it.
The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.
Have a play with Rubular: http://rubular.com/
But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.
'abcdefg' =~ /\Aabc/
from within the directory of "my_script.py" you can simply do:
%run ./my_script.py
Use four spaces to indent content between bullet points
1. item 1
2. item 2
```
Code block
```
3. item 3
Produces:
item 2
Code block
Adding to the above answers: To find the package name of installed apps on any android device: Go to Storage/Android/data/< package-name >
First, the valid syntax is
jQuery("input[name=ticketID]")
second, have you tried:
jQuery(":radio")
instead?
third, why not assign a class to all the radio buttons, and select them by class?
I had this issue for days and nothing I found anywhere online helped me, I'm posting my answer here in case it helps anyone else.
In my case, I was working on a microservice being called through remoting, and my @Transactional annotation at the service level was not being picked up by the remote proxy.
Adding a delegate class between the service and dao layers and marking the delegate method as transactional fixed this for me.
I have a solution which works well but instead an ellipsis it uses a gradient. It works when you have dynamic text so you don't know if it will be long enough to need an ellipse. The advantages are that you don't have to do any JavaScript calculations and it works for variable width containers including table cells and is cross-browser. It uses a couple of extra divs, but it's very easy to implement.
Markup:
<td>
<div class="fade-container" title="content goes here">
content goes here
<div class="fade">
</div>
</td>
CSS:
.fade-container { /*two lines*/
overflow: hidden;
position: relative;
line-height: 18px;
/* height must be a multiple of line-height for how many rows you want to show (height = line-height x rows) */
height: 36px;
-ms-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
word-wrap: break-word;
}
.fade {
position: absolute;
top: 50%;/* only cover the last line. If this wrapped to 3 lines it would be 33% or the height of one line */
right: 0;
bottom: 0;
width: 26px;
background: linear-gradient(to right, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
}
blog post: http://salzerdesign.com/blog/?p=453
example page: http://salzerdesign.com/test/fade.html
I don't see any answers yet that mention performance. Passing Func<>
s into Where()
or Count()
is bad. Real bad. If you use a Func<>
then it calls the IEnumerable
LINQ stuff instead of IQueryable
, which means that whole tables get pulled in and then filtered. Expression<Func<>>
is significantly faster, especially if you are querying a database that lives another server.
whats actually wrong with:
input { border: 1px solid #f00; }
do you only want it on inputs with errors? in that case give the input a class of error...
input.error { border: 1px solid #f00; }
I have solved this problem by importing the following dependency. you must manually import httpclient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
Because you're returning from the first method call, the second doesn't execute.
Try something like
OnClientClick="var b = validateView();ShowDiv1(); return b"
or reverse the situation,
OnClientClick="ShowDiv1();return validateView();"
or if there is a dependency of div1 on the validation routine.
OnClientClick="var b = validateView(); if (b) ShowDiv1(); return b"
What might be best is to encapsulate multiple inline statements into a mini function like so, to simplify the call:
// change logic to suit taste
function clicked() {
var b = validateView();
if (b)
ShowDiv1()
return b;
}
and then
OnClientClick="return clicked();"
I realize this is a very old question, but I thought I would offer an analogy to help illustrate the fine answers above.
If you walk into a public library, you will find that the books are all arranged in a particular order (most likely the Dewey Decimal System, or DDS). This corresponds to the "clustered index" of the books. If the DDS# for the book you want was 005.7565 F736s
, you would start by locating the row of bookshelves that is labeled 001-099
or something like that. (This endcap sign at the end of the stack corresponds to an "intermediate node" in the index.) Eventually you would drill down to the specific shelf labelled 005.7450 - 005.7600
, then you would scan until you found the book with the specified DDS#, and at that point you have found your book.
But if you didn't come into the library with the DDS# of your book memorized, then you would need a second index to assist you. In the olden days you would find at the front of the library a wonderful bureau of drawers known as the "Card Catalog". In it were thousands of 3x5 cards -- one for each book, sorted in alphabetical order (by title, perhaps). This corresponds to the "non-clustered index". These card catalogs were organized in a hierarchical structure, so that each drawer would be labeled with the range of cards it contained (Ka - Kl
, for example; i.e., the "intermediate node"). Once again, you would drill in until you found your book, but in this case, once you have found it (i.e, the "leaf node"), you don't have the book itself, but just a card with an index number (the DDS#) with which you could find the actual book in the clustered index.
Of course, nothing would stop the librarian from photocopying all the cards and sorting them in a different order in a separate card catalog. (Typically there were at least two such catalogs: one sorted by author name, and one by title.) In principle, you could have as many of these "non-clustered" indexes as you want.
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
Just add this to your code Controller
return response()->json(compact('token'))->header("Access-Control-Allow-Origin", "*");
You can use the below code to submit the form using JavaScript:
document.getElementById('FormID').submit();
Here is an example of initializing a boolean[][]:
const n = 8; // or some dynamic value
const palindrome: boolean[][] = new Array(n)
.fill(false)
.map(() => new Array(n)
.fill(false));
varbinary(max)
is the way to go (introduced in SQL Server 2005)
The dynamic way of implement whereNotIn:
$users = User::where('status',0)->get();
foreach ($users as $user) {
$data[] = $user->id;
}
$available = User::orderBy('name', 'DEC')->whereNotIn('id', $data)->get();
If you cannot put 1 column, you can simply put 2 column in the middle... (I am just combining answers) For Bootstrap 3
<div class="row">
<div class="col-lg-5 ">5 columns left</div>
<div class="col-lg-2 col-centered">2 column middle</div>
<div class="col-lg-5">5 columns right</div>
</div>
Even, you can text centered column by adding this to style:
.col-centered{
display: block;
margin-left: auto;
margin-right: auto;
text-align: center;
}
Additionally, there is another solution here
From my limited experience, I would say that the following two scenario could cause response status code: 0
, keep in mind; their could be more, but I know of those two:
the thing is, status: 0
is slightly generic, and their could be more use cases that trigger an empty response body.
I lately came up with this error. But it was even more odd. I was working on Android N and everything was going smoothly OK, until I test it on JellyBeans and Lollipop. In which I kept on getting the same DB error.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database 06-10 23:07:03.641: E/SQLiteDatabase(4419):
I had the right permissions in my manifest, including:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
The problem was this line in my DataBaseHelper.java:
private static String DB_PATH = "/data/data/com.example.quotes/databases";
which needed to be loaded from the context this way:
String DB_PATH = getContext().getApplicationInfo().dataDir+"/databases/";
Now is working properly form SDK 17.
package javaexception;
public class JavaException {
void show() throws Exception
{
throw new Exception("my.own.Exception");
}
void show2() throws Exception // Why throws is necessary here ?
{
show();
}
void show3() throws Exception // Why throws is necessary here ?
{
show2();
}
public static void main(String[] args) {
JavaException a = new JavaException();
try{
a.show3();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.
If you are using Master Pages then create a blank master page use that master page in your content page. If this resolve the problem then it means your original master page have some problem. Port your original code step by step to new master page and test after each port if intellisense is working properly. This trick solved my intellisense problem.
I have spent some time trying to figure out the difference.
And i think the factory function uses the module pattern and service function uses the standard java script constructor pattern.
Try:
String str = "my string \n my other string";
When printed you will get:
my string
my other string
Reference taken from this Blog.
You can use below to query to find row count.
Using pg_class:
SELECT reltuples::bigint AS EstimatedCount
FROM pg_class
WHERE oid = 'public.TableName'::regclass;
Using pg_stat_user_tables:
SELECT
schemaname
,relname
,n_live_tup AS EstimatedCount
FROM pg_stat_user_tables
ORDER BY n_live_tup DESC;
The first thing you should check for is the file permission of /etc/ssl
and /etc/ssl/certs
.
I made the mistake of dropping file permissions (or blowing away the SSL rm -rf /etc/ssl/*
directories) when using ssl-cert
group name/ID while working on my Certificate Authority Management Tool.
It was then that I noticed the exact same error message for wget
and curl
CLI browser tools:
server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
Once I brought the /etc/ssl
and /etc/ssl/cert
directories' file permission up to o+rx-w
, those CLI browser tools started to breath a bit easier:
mkdir -p /etc/ssl/certs
chmod u+rwx,go+rx /etc/ssl /etc/ssl/certs
I also had to recreate Java subdirectory and reconstruct the Trusted CA certificate directories:
mkdir /etc/ssl/certs/java
chmod u+rwx,go+rx /etc/ssl/certs/java
update-ca-certificates
and the coast was clear.
You have to rename Organization Identifier on Bundle Identifier on settings tab.
Only by renaming the Organization Identifier error will remove.
The 'Z' is what adds the timezone info. As for output UTC, that seems to be the subject of some confusion -- people seem to gravitate toward moment.js.
Borrowing from this answer, you could do something like this without moment.js:
controller
var app1 = angular.module('app1',[]);
app1.controller('ctrl',['$scope',function($scope){
var toUTCDate = function(date){
var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return _utc;
};
var millisToUTCDate = function(millis){
return toUTCDate(new Date(millis));
};
$scope.toUTCDate = toUTCDate;
$scope.millisToUTCDate = millisToUTCDate;
}]);
template
<html ng-app="app1">
<head>
<script data-require="angular.js@*" data-semver="1.2.12" src="http://code.angularjs.org/1.2.12/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ctrl">
<div>
utc {{millisToUTCDate(1400167800) | date:'dd-M-yyyy H:mm'}}
</div>
<div>
local {{1400167800 | date:'dd-M-yyyy H:mm'}}
</div>
</div>
</body>
</html>
here's plunker to play with it
Also note that with this method, if you use the 'Z' from Angular's date filter, it seems it will still print your local timezone offset.
If you only want to have a list of large files, then I'd like to provide you with the following one-liner:
join -o "1.1 1.2 2.3" <(git rev-list --objects --all | sort) <(git verify-pack -v objects/pack/*.idx | sort -k3 -n | tail -5 | sort) | sort -k3 -n
Whose output will be:
commit file name size in bytes
72e1e6d20... db/players.sql 818314
ea20b964a... app/assets/images/background_final2.png 6739212
f8344b9b5... data_test/pg_xlog/000000010000000000000001 1625545
1ecc2395c... data_development/pg_xlog/000000010000000000000001 16777216
bc83d216d... app/assets/images/background_1forfinal.psd 95533848
The last entry in the list points to the largest file in your git history.
You can use this output to assure that you're not deleting stuff with BFG you would have needed in your history.
Be aware, that you need to clone your repository with --mirror
for this to work.
TROUBLESHOOTING STEPS (Doc ID 730066.1)
Connection Timeout errors ORA-3135 and ORA-3136 A connection timeout error can be issued when an attempt to connect to the database does not complete its connection and authentication phases within the time period allowed by the following: SQLNET.INBOUND_CONNECT_TIMEOUT and/or INBOUND_CONNECT_TIMEOUT_ server-side parameters.
Starting with Oracle 10.2, the default for these parameters is 60 seconds where in previous releases it was 0, meaning no timeout.
On a timeout, the client program will receive the ORA-3135 (or possibly TNS-3135) error:
ORA-3135 connection lost contact
and the database will log the ORA-3136 error in its alert.log:
... Sat May 10 02:21:38 2008 WARNING: inbound connection timed out (ORA-3136) ...
When a database session is in the authentication phase, it will issue a sequence of SQL statements. The authentication is not complete until all these are parsed, executed, fetched completely. Some of the SQL statements in this list e.g. on 10.2 are:
select value$ from props$ where name = 'GLOBAL_DB_NAME'
select privilege#,level from sysauth$ connect by grantee#=prior privilege#
and privilege#>0 start with grantee#=:1 and privilege#>0
select SYS_CONTEXT('USERENV', 'SERVER_HOST'), SYS_CONTEXT('USERENV', 'DB_UNIQUE_NAME'),
SYS_CONTEXT('USERENV', 'INSTANCE_NAME'), SYS_CONTEXT('USERENV', 'SERVICE_NAME'),
INSTANCE_NUMBER, STARTUP_TIME, SYS_CONTEXT('USERENV', 'DB_DOMAIN')
from v$instance where INSTANCE_NAME=SYS_CONTEXT('USERENV', 'INSTANCE_NAME')
select privilege# from sysauth$ where (grantee#=:1 or grantee#=1) and privilege#>0
ALTER SESSION SET NLS_LANGUAGE= 'AMERICAN' NLS_TERRITORY= 'AMERICA' NLS_CURRENCY= '$'
NLS_ISO_CURRENCY= 'AMERICA' NLS_NUMERIC_CHARACTERS= '.,' NLS_CALENDAR= 'GREGORIAN'
NLS_DATE_FORMAT= 'DD-MON-RR' NLS_DATE_LANGUAGE= 'AMERICAN' NLS_SORT= 'BINARY' TIME_ZONE= '+02:00'
NLS_COMP= 'BINARY' NLS_DUAL_CURRENCY= '$' NLS_TIME_FORMAT= 'HH.MI.SSXFF AM' NLS_TIMESTAMP_FORMAT=
'DD-MON-RR HH.MI.SSXFF AM' NLS_TIME_TZ_FORMAT= 'HH.MI.SSXFF AM TZR' NLS_TIMESTAMP_TZ_FORMAT=
'DD-MON-RR HH.MI.SSXFF AM TZR'
NOTE: The list of SQL above is not complete and does not represent the ordering of the authentication SQL . Differences may also exist from release to release.
The above SQL statements need to be Parsed, Executed and Fetched as happens for all SQL inside an Oracle Database. It follows that any problem encountered during these phases which appears as a hang or severe slow performance may result in a timeout.
Symptoms of such hangs will be seen by the authenticating session as waits for: • cursor: pin S wait on X • latch: row cache objects • row cache lock Other types of wait events are possible; this list may not be complete.
The issue here is that the authenticating session is blocked waiting to get a shared resource which is held by another session inside the database. That blocker session is itself occupied in a long-running activity (or its own hang) which prevents it from releasing the shared resource needed by the authenticating session in a timely fashion. This results in the timeout being eventually reported to the authenticating session.
In such situations, we need to find out the blocker process holding the shared resource needed by the authenticating session in order to see what is happening to it.
Typical diagnostics used in such cases are the following:
$ sqlplus -prelim '/ as sysdba' oradebug setmypid oradebug unlimit oradebug dump systemstate 266 ...wait 90 seconds oradebug dump systemstate 266 ...wait 90 seconds oradebug dump systemstate 266 quit
Examples of issues which can result in Authentication hangs
Unpublished Bug 7039896 workaround parameter _enable_shared_pool_durations=false see Note 7039896.8
Other approaches to avoid the problem
In some cases, it may be possible to avoid problems with Authentication SQL by pinning such statements in the Shared Pool soon after the instance is started and they are freshly loaded. You can use the following artcile to advise on this: Document 726780.1 How to Pin a Cursor in the Shared Pool using DBMS_SHARED_POOL.KEEP
Pinning will prevent them from being flushed out due to inactivity and aging and will therefore prevent them for needing to be reloaded in the future i.e. needing to be reparsed and becoming susceptible to Authentication hang issues.
When I had this issue the cause was a relative reference to template files when using the ui.bootstrap.modal module.
templateUrl: 'js/templates/modal.html'
This works from a root domain (www.example.com) but when a path is added (www.example.com/path/) the reference breaks. The answer in my case was simply to making the reference absolute (js/ -> /js/).
templateUrl: '/js/templates/modal.html'
I had the same issue. When I checked my config file I noticed that 'fetch = +refs/heads/:refs/remotes/origin/' was on the same line as 'url = Z:/GIT/REPOS/SEL.git' as shown:
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "origin"]
url = Z:/GIT/REPOS/SEL.git fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
[gui]
wmstate = normal
geometry = 1109x563+32+32 216 255
At first I did not think that this would have mattered but after seeing the post by Magere I moved the line and that fixed the problem:
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
[remote "origin"]
url = Z:/GIT/REPOS/SEL.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
[gui]
wmstate = normal
geometry = 1109x563+32+32 216 255
With RestAssurd you can also do the following:
String path = baseApiUrl; //This is the base url of the API tested
URL url = new URL(path);
given(). //Rest Assured syntax
contentType("application/json"). //API content type
given().header("headerName", "headerValue"). //Some API contains headers to run with the API
when().
get(url).
then().
statusCode(200); //Assert that the response is 200 - OK
http://code.google.com/p/google-api-javascript-client/wiki/Authentication
See the area where it reads:
Setting up Authentication
The client's implementation of OAuth 2.0 uses a popup window to prompt the user to sign-in and approve the application. The first call to gapi.auth.authorize can trigger popup blockers, as it opens the popup window indirectly. To prevent the popup blocker from triggering on auth calls, call gapi.auth.init(callback) when the client loads. The supplied callback will be executed when the library is ready to make auth calls.
I would guess its relating to the real answer above in how it explains if there is an immediate response, it won't trip the popup alarm. The "gapi.auth.init" is making it so the api happens immediately.
Practical Application
I made an open source authentication microservice using node passport on npm and the various passport packages for each provider. I used a standard redirect approach to the 3rd party giving it a redirect URL to come back to. This was programmatic so I could have different places to redirect back to if login/signup and on particular pages.
var http=require('http');
http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary', function(res){
var str = '';
console.log('Response is '+res.statusCode);
res.on('data', function (chunk) {
str += chunk;
});
res.on('end', function () {
console.log(str);
});
});
Maybe this can help you
Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
id[i] = c.getInt(c.getColumnIndex("field_name"));
i++;
} while (c.moveToNext());
c.close();
}
You can use the mysqli multi_query function as below:
$sql = file_get_contents('mysqldump.sql');
$mysqli = new mysqli("localhost", "root", "pass", "testdb");
/* execute multi query */
$mysqli->multi_query($sql);
There is an overload with 3 arguments. Html.DropdownList(name, selectList, optionLabel)
Update: there was a typo in the below code snippet.
@Html.DropDownList("Cat", new SelectList(ViewBag.Categories,"ID", "CategoryName"), "-Select Category-")
For the validator use
@Html.ValidationMessage("Cat")
If you want to play nice with Windows file paths (under Cygwin) you can also try this:
fname=${fullfile##*[/|\\]}
This will account for backslash separators when using BaSH on Windows.
I found the proper solution for this error! Either you don't have any database installed or your default database in this file config/database.php is set to some other database like this
'default' => 'sqlite',
'default' => env('DB_CONNECTION', 'sqlite'), //laravel 5.2
change the default to which one you have installed or install that database which is made to be default! I had installed mysql and php artisan migrate worked after i changed that line to this:
'default' => 'mysql',
'default' => env('DB_CONNECTION', 'mysql'), //laravel5.2
Perhaps you need to know how urls are mapped too, since I suffered 404
for hours. There are two kinds of handlers handling requests. BeanNameUrlHandlerMapping
and SimpleUrlHandlerMapping
. When we defined a servlet-mapping
, we are using SimpleUrlHandlerMapping
. One thing we need to know is these two handlers share a common property called alwaysUseFullPath
which defaults to false
.
false
here means Spring will not use the full path to mapp a url to a controller. What does it mean? It means when you define a servlet-mapping
:
<servlet-mapping>
<servlet-name>viewServlet</servlet-name>
<url-pattern>/perfix/*</url-pattern>
</servlet-mapping>
the handler will actually use the *
part to find the controller. For example, the following controller will face a 404
error when you request it using /perfix/api/feature/doSomething
@Controller()
@RequestMapping("/perfix/api/feature")
public class MyController {
@RequestMapping(value = "/doSomething", method = RequestMethod.GET)
@ResponseBody
public String doSomething(HttpServletRequest request) {
....
}
}
It is a perfect match, right? But why 404
. As mentioned before, default value of alwaysUseFullPath
is false, which means in your request, only /api/feature/doSomething
is used to find a corresponding Controller, but there is no Controller cares about that path. You need to either change your url to /perfix/perfix/api/feature/doSomething
or remove perfix
from MyController base @RequestingMapping
.
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
I'm Using Windows 8.1 and I use this command
c:\wamp\bin\mysql\mysql5.6.12\bin\mysql.exe
instead of
c:\wamp\bin\mysql\mysql5.6.12\bin\mysqld
and it works fine..
Why don't you set both Background & BorderBrush
by same brush
<Style TargetType="{x:Type Button}" >
<Setter Property="Background" Value="{StaticResource marginBackGround}"></Setter>
<Setter Property="BorderBrush" Value="{StaticResource marginBackGround}"></Setter>
</Style>
<LinearGradientBrush x:Key="marginBackGround" EndPoint=".5,1" StartPoint="0.5,0">
<GradientStop Color="#EE82EE" Offset="0"/>
<GradientStop Color="#7B30B6" Offset="0.5"/>
<GradientStop Color="#510088" Offset="0.5"/>
<GradientStop Color="#76209B" Offset="0.9"/>
<GradientStop Color="#C750B9" Offset="1"/>
</LinearGradientBrush>
What's wrong with
func (e *Easy)SetStringOption(option Option, param string)
func (e *Easy)SetLongOption(option Option, param long)
and so on?
You can simply concatnate two lists, e.g:
list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2
print(list3)
>> [0, 1, 2, 3]
This is a constructor:
function MyClass() {}
When you do
var myObj = new MyClass();
MyClass
is executed, and a new object is returned of that class.
If you are looking for a fast unrolled version, this should do the trick, assuming a byte array called "b" with a length of 8:
byte[] -> long
long l = ((long) b[7] << 56)
| ((long) b[6] & 0xff) << 48
| ((long) b[5] & 0xff) << 40
| ((long) b[4] & 0xff) << 32
| ((long) b[3] & 0xff) << 24
| ((long) b[2] & 0xff) << 16
| ((long) b[1] & 0xff) << 8
| ((long) b[0] & 0xff);
long -> byte[] as an exact counterpart to the above
byte[] b = new byte[] {
(byte) lng,
(byte) (lng >> 8),
(byte) (lng >> 16),
(byte) (lng >> 24),
(byte) (lng >> 32),
(byte) (lng >> 40),
(byte) (lng >> 48),
(byte) (lng >> 56)};
You can use the short version:
File.write('/path/to/file', 'Some glorious content')
It returns the length written; see ::write for more details and options.
To append to the file, if it already exists, use:
File.write('/path/to/file', 'Some glorious content', mode: 'a')
Definitely the easiest way to do that is using Gson's default parsing function fromJson()
.
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType
(e.g., any List
), which is fromJson(JsonElement json, Type typeOfT)
.
In your case, you just need to get the Type
of a List<String>
and then parse the JSON array into that Type
, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson
is a JsonElement
, but it could also be a String
, any Reader
or a JsonReader
.
You may want to take a look at Gson API documentation.
Not very pretty but here is another way:
String runFct =
queryType.equals("eq") ? "method1":
queryType.equals("L_L")? "method2":
queryType.equals("L_R")? "method3":
queryType.equals("L_LR")? "method4":
"method5";
Method m = this.getClass().getMethod(runFct);
m.invoke(this);
type on terminal:
nano ~/.bash_profile
then paste:
export PATH="/Users/yourusername/.composer/vendor/bin:$PATH"
then save (press ctrl+c, press Y, press enter)
now you are ready to use "laravel" on your terminal
You need to reference the namespace
using System.Windows.Form;
and then add in the code
protected void Button1_Click(object sender, EventArgs e)
{
MessageBox.Show(" Hi....");
}
As an extend to @Eugene's answer another version which will work to push code from local repo to master/develop branch .
Switch to branch ‘master’:
$ git checkout master
Merge from local repo to master:
$ git merge --no-ff FEATURE/<branch_Name>
Push to master:
$ git push
The same error occurred when I updated Windows. Tried everything. Nothing worked.
Finally, went to Device Manager-> Network Adapters Disabled and enabled the Virtualbox Host only Adapter
And it worked!
The lookup module of ansible works fine for me. The yml is:
- hosts: test
vars:
time: "{{ lookup('pipe', 'date -d \"1 day ago\" +\"%Y%m%d\"') }}"
You can replace any command with date to get result of the command.
Try this,
IFS=''
while read line
do
echo $line
done < file.txt
EDIT:
From man bash
IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with the read builtin command. The default value is
``<space><tab><newline>''
<td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>
That should do it.
Excerpt:-
try
{
cnt++;scnt++;now=System.currentTimeMillis();r=rand.nextInt(6);r++;
loc=lm.getLastKnownLocation(best);
if(loc!=null){lat=loc.getLatitude();lng=loc.getLongitude();}
Thread.sleep(100);
handler.sendMessage(handler.obtainMessage());
}
catch (InterruptedException e)
{
Toast.makeText(this, "Error="+e.toString(), Toast.LENGTH_LONG).show();
}
As you can see above, a thread is running alongside main thread of user-interface activity which continuously displays GPS lat,long alongwith current time and a random dice throw.
IF you are curious then just check the full code: GPS Location with a randomized dice throw & current time in separate thread
The simple way to open the link in a new tab is to add a target attribute in the link having a value equals to "_blanl", like this :
<a href="http://www.WEBSITE_NAME.com" target="_blank"></a>
_x000D_
In SSMS 2012, you'll have to use:
To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.
Alternatively you could add an endpoint to return your variable:
@app.route("/api/geocode")
def geo_code():
return jsonify(geocode)
Then do an XHR to retrieve it:
fetch('/api/geocode')
.then((res)=>{ console.log(res) })
I just did the following to change the type of an input:
$('#ID_of_element')[0].type = 'text';
and it works.
I was needing to do this because I was using jQuery UI datepickers' in an ASP NET Core 3.1 project and they were not working properly on Chromium-based browsers (see: https://stackoverflow.com/a/61296225/7420301).
The representation of the values 65529u and -7 are identical for 16-bit ints. Only the interpretation of the bits is different.
For larger ints and these values, you need to sign extend; one way is with logical operations
int y = (int )(x | 0xffff0000u); // assumes 16 to 32 extension, x is > 32767
If speed is not an issue, or divide is fast on your processor,
int y = ((int ) (x * 65536u)) / 65536;
The multiply shifts left 16 bits (again, assuming 16 to 32 extension), and the divide shifts right maintaining the sign.
All in all, the Xcode cannot find the position of library/header/framework, then you tell Xcode where they are.
set the path that Xcode use to find library/header/framework in Build Settings --> Library/Header/Framework Search Paths.
Say, now it cannot find -lGoogleAnalytics
, so you add the directory where -lGoogleAnalytics
is to the Library Search Paths.
Should you want to clear the array with something other than a value, std::file wont cut it; instead I found std::generate useful. e.g. I had a vector of lists I wanted to initialize
std::generate(v.begin(), v.end(), [] () { return std::list<X>(); });
You can do ints too e.g.
std::generate(v.begin(), v.end(), [n = 0] () mutable { return n++; });
or just
std::generate(v.begin(), v.end(), [] (){ return 0; });
but I imagine std::fill is faster for the simplest case
I think that there isn't a official naming convention to JSON, but you can follow some industry leaders to see how it is working.
Google, which is one of the biggest IT company of the world, has a JSON style guide: https://google.github.io/styleguide/jsoncstyleguide.xml
Taking advantage, you can find other styles guide, which Google defines, here: https://github.com/google/styleguide
Run the following command to find 8080 port number PID:
sudo lsof -t -i:8080
You can now easily kill your PID using following command:
sudo kill -9
You can use one command to to kill a process on a specific port using the following command:
sudo kill -9 $(sudo lsof -t -i:8000)
ECMAScript 6 introduced arrow functions so now the setTimeout() or setInterval() don't have to look like this:
setTimeout(function() { FetchData(); }, 1000)
Instead, you can use annonymous arrow function which looks cleaner, and less confusing:
setTimeout(() => {FetchData();}, 1000)
DateTime currentDateTime = DateTime.Now;
int week = (int) currentDateTime.DayOfWeek;
Not directly related, unless you have similar code but I just noticed a strange behaviour to form-inline, bootstrap 3.3.7
I did not use row and cells for this as it is a desktop project, if the opening tag was below table (in this case):
<table class="form-inline">
<form>
<tr>
Form elements would stack.
Switch and it properly lined up.
<form>
<table class="form-inline">
<tr>
Safari 10.0.2 and latest Chrome did not make any differences. Maybe my layout was wrong but it is not very forgiving.
you can test a color by writing the CSS inline like <div style="color:red";>...</div>
If you are a intellij IDE user, you can use shortcut key Alt+Enter
and then choose Wrap with Center
and then add textAlign: TextAlign.center
Another way of viewing the full content of the cells in a pandas dataframe is to use IPython's display functions:
from IPython.display import HTML
HTML(df.to_html())
The immediate cause of the problem is that the JDBC driver has attempted to read from a network Socket that has been closed by "the other end".
This could be due to a few things:
If the remote server has been configured (e.g. in the "SQLNET.ora" file) to not accept connections from your IP.
If the JDBC url is incorrect, you could be attempting to connect to something that isn't a database.
If there are too many open connections to the database service, it could refuse new connections.
Given the symptoms, I think the "too many connections" scenario is the most likely. That suggests that your application is leaking connections; i.e. creating connections and then failing to (always) close them.
Sure.
.orElseThrow(() -> new MyException(someArgument))
Assuming your table has auto-numbered field "RowID" and you want to select only records where RowID is even or odd.
To show odd:
Select * from MEN where (RowID % 2) = 1
To show even:
Select * from MEN where (RowID % 2) = 0
There are several and extensive pieces of software available from the astronomy and cosmology community - this is a significant area of research both historically and currently.
Do not be alarmed if you are not an astronomer - some are easy to use outside the field. For example, you could use astropy/photutils:
https://photutils.readthedocs.io/en/stable/detection.html#local-peak-detection
[It seems a bit rude to repeat their short sample code here.]
An incomplete and slightly biased list of techniques/packages/links that might be of interest is given below - do add more in the comments and I will update this answer as necessary. Of course there is a trade-off of accuracy vs compute resources. [Honestly, there are too many to give code examples in a single answer such as this so I am not sure whether this answer will fly or not.]
Source Extractor https://www.astromatic.net/software/sextractor
MultiNest https://github.com/farhanferoz/MultiNest [+ pyMultiNest]
ASKAP/EMU source-finding challenge: https://arxiv.org/abs/1509.03931
You could also search for Planck and/or WMAP source-extraction challenges.
...
Another application are intrusive lists. The element type can tell the list what its next/prev pointers are. So the list does not use hard-coded names but can still use existing pointers:
// say this is some existing structure. And we want to use
// a list. We can tell it that the next pointer
// is apple::next.
struct apple {
int data;
apple * next;
};
// simple example of a minimal intrusive list. Could specify the
// member pointer as template argument too, if we wanted:
// template<typename E, E *E::*next_ptr>
template<typename E>
struct List {
List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }
void add(E &e) {
// access its next pointer by the member pointer
e.*next_ptr = head;
head = &e;
}
E * head;
E *E::*next_ptr;
};
int main() {
List<apple> lst(&apple::next);
apple a;
lst.add(a);
}
Add the schema name to the entity and it will find it. Worked for me!
Close the tab of the page you disabled alerts. Re-open the page in a new tab. The setting only lasts for the session, so alerts will be re-enabled once the new session begins in the new tab.
I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c']
with render_template('show_entries.html', letters=letters)
, and set
var letters = {{ letters|safe }}
in my javascript code. Jinja2 replaced {{ letters }}
with ['a','b','c']
, which javascript interpreted as an array of strings.
Symmetric Key Cryptography : Symmetric key uses the same key for encryption and decryption. The main challenge with this type of cryptography is the exchange of the secret key between the two parties sender and receiver.
Example : The following example uses symmetric key for encryption and decryption algorithm available as part of the Sun's JCE(Java Cryptography Extension). Sun JCE is has two layers, the crypto API layer and the provider layer.
DES (Data Encryption Standard) was a popular symmetric key algorithm. Presently DES is outdated and considered insecure. Triple DES and a stronger variant of DES. It is a symmetric-key block cipher. There are other algorithms like Blowfish, Twofish and AES(Advanced Encryption Standard). AES is the latest encryption standard over the DES.
Steps :
KeyGenerator
and an algorithm to generate a secret key. We are using DESede
. UTF-8 encoding
. Cipher
with ENCRYPT_MODE
, use the secret key and encrypt the bytes. Cipher
with DECRYPT_MODE
, use the same secret key and decrypt the bytes. All the above given steps and concept are same, we just replace algorithms.
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class EncryptionDecryptionAES {
static Cipher cipher;
public static void main(String[] args) throws Exception {
/*
create key
If we need to generate a new key use a KeyGenerator
If we have existing plaintext key use a SecretKeyFactory
*/
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128); // block size is 128bits
SecretKey secretKey = keyGenerator.generateKey();
/*
Cipher Info
Algorithm : for the encryption of electronic data
mode of operation : to avoid repeated blocks encrypt to the same values.
padding: ensuring messages are the proper length necessary for certain ciphers
mode/padding are not used with stream cyphers.
*/
cipher = Cipher.getInstance("AES"); //SunJCE provider AES algorithm, mode(optional) and padding schema(optional)
String plainText = "AES Symmetric Encryption Decryption";
System.out.println("Plain Text Before Encryption: " + plainText);
String encryptedText = encrypt(plainText, secretKey);
System.out.println("Encrypted Text After Encryption: " + encryptedText);
String decryptedText = decrypt(encryptedText, secretKey);
System.out.println("Decrypted Text After Decryption: " + decryptedText);
}
public static String encrypt(String plainText, SecretKey secretKey)
throws Exception {
byte[] plainTextByte = plainText.getBytes();
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedByte = cipher.doFinal(plainTextByte);
Base64.Encoder encoder = Base64.getEncoder();
String encryptedText = encoder.encodeToString(encryptedByte);
return encryptedText;
}
public static String decrypt(String encryptedText, SecretKey secretKey)
throws Exception {
Base64.Decoder decoder = Base64.getDecoder();
byte[] encryptedTextByte = decoder.decode(encryptedText);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
String decryptedText = new String(decryptedByte);
return decryptedText;
}
}
Output:
Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: sY6vkQrWRg0fvRzbqSAYxepeBIXg4AySj7Xh3x4vDv8TBTkNiTfca7wW/dxiMMJl
Decrypted Text After Decryption: AES Symmetric Encryption Decryption
Example: Cipher with two modes, they are encrypt and decrypt. we have to start every time after setting mode to encrypt or decrypt a text.
Assuming you are always in Linux, try the find
cmd.
- name: Clean everything inside {{ item }}
shell: test -d {{ item }} && find {{ item }} -path '{{ item }}/*' -prune -exec rm -rf {} \;
with_items: [/home/mydata/web]
This should wipe out files/folders/hidden under /home/mydata/web
This is simply what to do:
datetime.datetime.now() - datetime.timedelta(minutes = 15)
timedelta
s are specifically designed to allow you to subtract or add deltas (differences) to datetime
s.
It is a little complicated, but you can draw all the objects by the following code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
if np.sum(np.abs(s-e)) == r[1]-r[0]:
ax.plot3D(*zip(s, e), color="b")
# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")
# draw a point
ax.scatter([0], [0], [0], color="g", s=100)
# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()
As you've figured out, Entity Framework can't actually run your C# code as part of its query. It has to be able to convert the query to an actual SQL statement. In order for that to work, you will have to restructure your query expression into an expression that Entity Framework can handle.
public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
string name = this.charityName;
string referenceNumber = this.referenceNumber;
return p =>
(string.IsNullOrEmpty(name) ||
p.registeredName.ToLower().Contains(name.ToLower()) ||
p.alias.ToLower().Contains(name.ToLower()) ||
p.charityId.ToLower().Contains(name.ToLower())) &&
(string.IsNullOrEmpty(referenceNumber) ||
p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}
Easiest way on Safari 11.0 macOS SIERRA 10.12.6: Reload Page From Origin, you can use help to find out where in the menu it is located, or you can use the shortcut option(alt) + command + R.
This query is search text in stored procedure from all databases.
DECLARE @T_Find_Text VARCHAR(1000) = 'Foo'
IF OBJECT_ID('tempdb..#T_DBNAME') IS NOT NULL DROP TABLE #T_DBNAME
IF OBJECT_ID('tempdb..#T_PROCEDURE') IS NOT NULL DROP TABLE #T_PROCEDURE
CREATE TABLE #T_DBNAME
(
IDX int IDENTITY(1,1) PRIMARY KEY
, DBName VARCHAR(255)
)
CREATE TABLE #T_PROCEDURE
(
IDX int IDENTITY(1,1) PRIMARY KEY
, DBName VARCHAR(255)
, Procedure_Name VARCHAR(MAX)
, Procedure_Description VARCHAR(MAX)
)
INSERT INTO #T_DBNAME (DBName)
SELECT name FROM master.dbo.sysdatabases
DECLARE @T_C_IDX INT = 0
DECLARE @T_C_DBName VARCHAR(255)
DECLARE @T_SQL NVARCHAR(MAX)
DECLARE @T_SQL_PARAM NVARCHAR(MAX)
SET @T_SQL_PARAM =
' @T_C_DBName VARCHAR(255)
, @T_Find_Text VARCHAR(255)
'
WHILE EXISTS(SELECT TOP 1 IDX FROM #T_DBNAME WHERE IDX > @T_C_IDX ORDER BY IDX ASC)
BEGIN
SELECT TOP 1
@T_C_DBName = DBName
FROM #T_DBNAME WHERE IDX > @T_C_IDX ORDER BY IDX ASC
SET @T_SQL = ''
SET @T_SQL = @T_SQL + 'INSERT INTO #T_PROCEDURE(DBName, Procedure_Name, Procedure_Description)'
SET @T_SQL = @T_SQL + 'SELECT SPECIFIC_CATALOG, ROUTINE_NAME, ROUTINE_DEFINITION '
SET @T_SQL = @T_SQL + 'FROM ' + @T_C_DBName + '.INFORMATION_SCHEMA.ROUTINES '
SET @T_SQL = @T_SQL + 'WHERE ROUTINE_DEFINITION LIKE ''%''+ @T_Find_Text + ''%'' '
SET @T_SQL = @T_SQL + 'AND ROUTINE_TYPE = ''PROCEDURE'' '
BEGIN TRY
EXEC SP_EXECUTESQL @T_SQL, @T_SQL_PARAM, @T_C_DBName, @T_Find_Text
END TRY
BEGIN CATCH
SELECT @T_C_DBName + ' ERROR'
END CATCH
SET @T_C_IDX = @T_C_IDX + 1
END
SELECT IDX, DBName, Procedure_Name FROM #T_PROCEDURE ORDER BY DBName ASC
wget -r --no-parent URL --user=username --password=password
the last two options are optional if you have the username and password for downloading, otherwise no need to use them.
You can also see more options in the link https://www.howtogeek.com/281663/how-to-use-wget-the-ultimate-command-line-downloading-tool/
One approach could be using find:
find /desired_location -type d -print0 | xargs -0 chmod 0755
find /desired_location -type f -print0 | xargs -0 chmod 0644
The accepted answer doesn't create a name-only attribute anymore (as of September 2017).
You should use JQuery prop() method to create name-only attributes.
$(body).prop('data-body', true)
Initializations with (...)
in the class body is not allowed. Use {..}
or = ...
. Unfortunately since the respective constructor is explicit
and vector
has an initializer list constructor, you need a functional cast to call the wanted constructor
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
As an alternative you can use constructor initializer lists
Attribute():name(5), val(5, 0) {}
Starting with react_router 1.0, the props will be passed onto the anchor tag. You can directly use target="_blank"
. Discussed here: https://github.com/ReactTraining/react-router/issues/2188
The command prompt wouldn't use JAVA_HOME to find javac.exe, it would use PATH.
You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)
You can use window.location to change your current page.
$('.entry a:first').click(function() {
window.location = "http://google.ca";
});
$("#select1").change(function() {_x000D_
if ($(this).data('options') === undefined) {_x000D_
/*Taking an array of all options-2 and kind of embedding it on the select1*/_x000D_
$(this).data('options', $('#select2 option').clone());_x000D_
}_x000D_
var id = $(this).val();_x000D_
var options = $(this).data('options').filter('[value=' + id + ']');_x000D_
$('#select2').html(options);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<select name="select1" id="select1">_x000D_
<option value="1">Fruit</option>_x000D_
<option value="2">Animal</option>_x000D_
<option value="3">Bird</option>_x000D_
<option value="4">Car</option>_x000D_
</select>_x000D_
_x000D_
_x000D_
<select name="select2" id="select2">_x000D_
<option value="1">Banana</option>_x000D_
<option value="1">Apple</option>_x000D_
<option value="1">Orange</option>_x000D_
<option value="2">Wolf</option>_x000D_
<option value="2">Fox</option>_x000D_
<option value="2">Bear</option>_x000D_
<option value="3">Eagle</option>_x000D_
<option value="3">Hawk</option>_x000D_
<option value="4">BWM<option>_x000D_
</select>
_x000D_
Using jQuery data() to store data
I guess hiding elements doesn't work cross-browser(2012), I have'nt tested it myself.
In Android you can create shared buffer between C++ and Java (with directAlloc method) and manipulate it in both sides.
Now click on Add a generic credential and provide the following values
(1) Internet or network adress: git:https://tfs.donamain name (2) username: your username (3) password: your password
this should fix it
Ideally you need to have .d.ts
file for typings to let Linting
work.
But It seems that d3gauge
doesn't have one, you can Ask the developers to provide and hope they will listen.
Alternatively, you can solve this specific issue by doing this
declare var drawGauge: any;
import '../../../../js/d3gauge.js';
export class MemMonComponent {
createMemGauge() {
new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js
}
}
If you use it in multiple files, you can create a d3gauage.d.ts
file with the content below
declare var drawGauge: any;
and reference it in your boot.ts
(bootstrap) file at the top, like this
///<reference path="../path/to/d3gauage.d.ts"/>
Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.
[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.
@Adrien's answer is not working. It gives an ORA-01791.
The correct answer (for the question that is asked) should be:
select id
from
(SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
UNION ALL
SELECT id, 1 as ordered FROM b -- returns 2,1
)
group by id
order by min(ordered)
Explanation:
This solves all the cases, even when table b has more or different elements then table a
Running the risk of getting another Necromancer badge, I would like to add one very good use for uintptr_t (or even intptr_t) and that is writing testable embedded code. I write mostly embedded code targeted at various arm and currently tensilica processors. These have various native bus width and the tensilica is actually a Harvard architecture with separate code and data buses that can be different widths. I use a test driven development style for much of my code which means I do unit tests for all the code units I write. Unit testing on actual target hardware is a hassle so I typically write everything on an Intel based PC either in Windows or Linux using Ceedling and GCC. That being said, a lot of embedded code involves bit twiddling and address manipulations. Most of my Intel machines are 64 bit. So if you are going to test address manipulation code you need a generalized object to do math on. Thus the uintptr_t give you a machine independent way of debugging your code before you try deploying to target hardware. Another issue is for the some machines or even memory models on some compilers, function pointers and data pointers are different widths. On those machines the compiler may not even allow casting between the two classes, but uintptr_t should be able to hold either. -- Edit -- Was pointed out by @chux, this is not part of the standard and functions are not objects in C. However it usually works and since many people don't even know about these types I usually leave a comment explaining the trickery. Other searches in SO on uintptr_t will provide further explanation. Also we do things in unit testing that we would never do in production because breaking things is good.
DATEDIFF(hour, start_date, end_date)
will give you the number of hour boundaries crossed between start_date
and end_date
.
If you need the number of fractional hours, you can use DATEDIFF
at a higher resolution and divide the result:
DATEDIFF(second, start_date, end_date) / 3600.0
The documentation for DATEDIFF
is available on MSDN:
http://msdn.microsoft.com/en-us/library/ms189794%28SQL.105%29.aspx
If you want an else
you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value
as the statement instead, and remove the filter from the end:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
How about something like this.
Test the live example: http://jsfiddle.net/6hBZU/1/
It assumes that the string will always end with the extension:
function openFile(file) {
var extension = file.substr( (file.lastIndexOf('.') +1) );
switch(extension) {
case 'jpg':
case 'png':
case 'gif':
alert('was jpg png gif'); // There's was a typo in the example where
break; // the alert ended with pdf instead of gif.
case 'zip':
case 'rar':
alert('was zip rar');
break;
case 'pdf':
alert('was pdf');
break;
default:
alert('who knows');
}
};
openFile("somestring.png");
EDIT: I mistakenly deleted part of the string in openFile("somestring.png");
. Corrected. Had it in the Live Example, though.
I create a block to reset all my sequences:
DECLARE
I_val number;
BEGIN
FOR US IN
(SELECT US.SEQUENCE_NAME FROM USER_SEQUENCES US)
LOOP
execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;
execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by -' || l_val || ' minvalue 0';
execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;
execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by 1 minvalue 0';
END LOOP;
END;
$col = $db->query("SHOW COLUMNS FROM category");
while ($fildss = $col->fetch_array())
{
$filds[] = '"{'.$fildss['Field'].'}"';
$values[] = '$rows->'.$fildss['Field'].'';
}
if($type == 'value')
{
return $values = implode(',', $values);
}
else {
return $filds = implode(',', $filds);
}
SELECT * FROM `orders` WHERE `order_date_time` BETWEEN 1534809600 AND 1536718364
Encapsulate hides variables or some implementation that may be changed so often in a class to prevent outsiders access it directly. They must access it via getter and setter methods.
Abstraction is used to hiding something too but in a higher degree(class, interface). Clients use an abstract class(or interface) do not care about who or which it was, they just need to know what it can do.
For those who struggled for a while wonderring why the selected answer does not work:
ps -p <pid> -o %cpu,%mem
No SPACE ibetween %cpu,
and %mem
.
I think this is a simple example, how to check if a radio in a group of radios was checked.
if($('input[name=html_elements]:checked').length){
//a radio button was checked
}else{
//there was no radio button checked
}
In case you need the []
syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:
[routerLink]="['edit', business._id]"
As for an "about page" with no parameters like yours,
[routerLink]="/about"
or
[routerLink]=['about']
will do the trick.
I like this one:
very slick with only this as HTML and the rest CSS3 that is backwards compatible (although it will have less eyecandy)
Edit Added code below, but taken directly from the page above, all credit to that author
.meter {_x000D_
height: 20px;_x000D_
/* Can be anything */_x000D_
position: relative;_x000D_
background: #555;_x000D_
-moz-border-radius: 25px;_x000D_
-webkit-border-radius: 25px;_x000D_
border-radius: 25px;_x000D_
padding: 10px;_x000D_
-webkit-box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
-moz-box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);_x000D_
}_x000D_
_x000D_
.meter>span {_x000D_
display: block;_x000D_
height: 100%;_x000D_
-webkit-border-top-right-radius: 8px;_x000D_
-webkit-border-bottom-right-radius: 8px;_x000D_
-moz-border-radius-topright: 8px;_x000D_
-moz-border-radius-bottomright: 8px;_x000D_
border-top-right-radius: 8px;_x000D_
border-bottom-right-radius: 8px;_x000D_
-webkit-border-top-left-radius: 20px;_x000D_
-webkit-border-bottom-left-radius: 20px;_x000D_
-moz-border-radius-topleft: 20px;_x000D_
-moz-border-radius-bottomleft: 20px;_x000D_
border-top-left-radius: 20px;_x000D_
border-bottom-left-radius: 20px;_x000D_
background-color: #f1a165;_x000D_
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #f1a165), color-stop(1, #f36d0a));_x000D_
background-image: -webkit-linear-gradient(top, #f1a165, #f36d0a);_x000D_
background-image: -moz-linear-gradient(top, #f1a165, #f36d0a);_x000D_
background-image: -ms-linear-gradient(top, #f1a165, #f36d0a);_x000D_
background-image: -o-linear-gradient(top, #f1a165, #f36d0a);_x000D_
-webkit-box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);_x000D_
-moz-box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="meter">_x000D_
<span style="width: 33%"></span>_x000D_
<!-- I use my viewmodel in MVC to calculate the progress and then use @Model.progress to place it in my HTML with Razor -->_x000D_
</div>
_x000D_
You need to use convert in order by as well:
SELECT Convert(varchar,A.InsertDate,103) as Tran_Date
order by Convert(varchar,A.InsertDate,103)
In my case, I needed to allow many inactives and only one combination of two keys active, like this:
UUL_USR_IDF UUL_UND_IDF UUL_ATUAL
137 18 0
137 19 0
137 20 1
137 21 0
This seems to work:
CREATE UNIQUE NONCLUSTERED INDEX UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL
ON USER_UND(UUL_USR_IDF, UUL_ATUAL)
WHERE UUL_ATUAL = 1;
Here are my test cases:
SELECT * FROM USER_UND WHERE UUL_USR_IDF = 137
insert into USER_UND values (137, 22, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 23, 0) --I CAN
insert into USER_UND values (137, 24, 0) --I CAN
DELETE FROM USER_UND WHERE UUL_USR_ID = 137
insert into USER_UND values (137, 22, 1) --I CAN
insert into USER_UND values (137, 27, 1) --I CAN NOT => Cannot insert duplicate key row in object 'dbo.USER_UND' with unique index 'UQ_USR_UND_UUL_USR_IDF_UUL_ATUAL'. The duplicate key value is (137, 1).
insert into USER_UND values (137, 28, 0) --I CAN
insert into USER_UND values (137, 29, 0) --I CAN
As of Room 2.2.0 released October 2019, you can specify a Target Entity for updates. Then if the update parameter is different, Room will only update the partial entity columns. An example for the OP question will show this a bit more clearly.
@Update(entity = Tour::class)
fun update(obj: TourUpdate)
@Entity
public class TourUpdate {
@ColumnInfo(name = "id")
public long id;
@ColumnInfo(name = "endAddress")
private String endAddress;
}
Notice you have to a create a new partial entity called TourUpdate, along with your real Tour entity in the question. Now when you call update with a TourUpdate object, it will update endAddress and leave the startAddress value the same. This works perfect for me for my usecase of an insertOrUpdate method in my DAO that updates the DB with new remote values from the API but leaves the local app data in the table alone.
TL;DR: Check the path to your keystore.jks
file.
In my case, here's what happened:
I moved the project folder of my entire app to another location on my PC. Much later, I wanted to generate a signed apk file. Unknown to me, the default location of the path to my keystore.jks
had been reset to a wrong location and I had clicked okay. Since it could not find a keystore at the path I selected, I got that error.
The solution was to check whether the path to my keystore.jks
file was correct.
The python libs are obsolete with this function. I've done one that works correctly:
import os
import shutil
def copydirectorykut(src, dst):
os.chdir(dst)
list=os.listdir(src)
nom= src+'.txt'
fitx= open(nom, 'w')
for item in list:
fitx.write("%s\n" % item)
fitx.close()
f = open(nom,'r')
for line in f.readlines():
if "." in line:
shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
else:
if not os.path.exists(dst+'/'+line[:-1]):
os.makedirs(dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
f.close()
os.remove(nom)
os.chdir('..')
Check this: https://github.com/plank/MarkerClusterer
This is the MarkerCluster modified to have a infoWindow in a cluster marker, when you have several markers in the same position.
You can see how it works here: http://culturedays.ca/en/2013-activities
How about this :
@client = TinyTds::Client.new(
:adapter => 'mysql2',
:host => 'host',
:database => 'siteconfig_development',
:username => 'username',
:password => 'password'
sql = "SELECT * FROM users"
result = @client.execute(sql)
results.each do |row|
puts row[0]
end
You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record
In PHP 5.3 or greater, you can get it like this:
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
You can use following approach:
import org.apache.commons.codec.binary.Base64;
// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));
// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));
Hope this answers your doubt.
It is recommended to use the spinal-case (which is highlighted by RFC3986), this case is used by Google, PayPal, and other big companies.
source:- https://blog.restcase.com/5-basic-rest-api-design-guidelines/
image: reporting services line chart horizontal axis properties
To see all dates on the report; Set Axis Type to Scalar, Set Interval to 1 -Jump Labels section Set disable auto-fit set label rotation angle as you desire.
These would help.
In Angular 10, this is what works for me: In the HTML:
<mat-table [dataSource]="myArray">
In the component TS:
myArray: MyObject[] = [];
addObjectToTable(object:MyObject): void {
//TO PREVENT DUPLICATED OBJECTS
if (object&& !this.myArray.includes(object)) {
this.myArray.push(object);
// TO FORCE DATA-TABLE's DATASOURCE TO REFRESH
this.myArray= [...this.myArray];
}
}
Sorry for the necro on this post, but I feel compelled to weigh in on a couple of things that do not seem to have been touched on.
First a foremost - when we find ourselves needing access to private members on a class during unit testing, it is generally a big, fat red flag that we've goofed in our strategic or tactical approach and have inadvertently violated the single responsibility principal by pushing behavior where it does not belong. Feeling the need to access methods that are really nothing more than an isolated subroutine of a construction procedure is one of the most common occurrences of this; however, it's kind of like your boss expecting you to show up for work ready-to-go and also having some perverse need to know what morning routine you went through to get you into that state...
The other most common instance of this happening is when you find yourself trying to test the proverbial "god class." It is a special kind of problem in and of itself, but suffers from the same basic issue with needing to know intimate details of a procedure - but that's getting off topic.
In this specific example, we've effectively assigned the responsibility of fully initializing the Bar object to the FooBar class's constructor. In object oriented programming, one of the core tenents is that the constructor is "sacred" and should be guarded against invalid data that would invalidate its' own internal state and leave it primed to fail somewhere else downstream (in what could be a very deep pipeline.)
We've failed to do that here by allowing the FooBar object to accept a Bar that is not ready at the time that the FooBar is constructed, and have compensated by sort-of "hacking" the FooBar object to take matters into its' own hands.
This is the result of a failure to adhere to another tenent of object oriented programming (in the case of Bar,) which is that an object's state should be fully initialized and ready to handle any incoming calls to its' public members immediately after creation. Now, this does not mean immediately after the constructor is called in all instances. When you have an object that has many complex construction scenarios, then it is better to expose setters to its optional members to an object that is implemented in accordance with a creation design-pattern (Factory, Builder, etc...) In any of the latter cases, you would be pushing the initialization of the target object off into another object graph whose sole purpose is directing traffic to get you to a point where you have a valid instance of that which you are requesting - and the product should not be considered "ready" until after this creation object has served it up.
In your example, the Bar's "status" property does not seem to be in a valid state in which a FooBar can accept it - so the FooBar does something to it to correct that issue.
The second issue I am seeing is that it appears that you are trying to test your code rather than practice test-driven development. This is definitely my own opinion at this point in time; but, this type of testing is really an anti-pattern. What you end up doing is falling into the trap of realizing that you have core design problems that prevent your code from being testable after the fact, rather than writing the tests you need and subsequently programming to the tests. Either way you come at the problem, you should still end up with the same number of tests and lines of code had you truly achieved a SOLID implementation. So - why try and reverse engineer your way into testable code when you can just address the matter at the onset of your development efforts?
Had you done that, then you would have realized much earlier on that you were going to have to write some rather icky code in order to test against your design and would have had the opportunity early on to realign your approach by shifting behavior to implementations that are easily testable.
Simply:
UIView
as wrapper with auto layout to views around. UILabel
inside that wrapper. Add constraints that will stick tyour label to edges of wrapper.UIButton
inside your wrapper, then simple add the same constraints as you did for UILabel
.Here is an awesome and precise explanation I found.
TIMESTAMP used to track changes of records, and update every time when the record is changed. DATETIME used to store specific and static value which is not affected by any changes in records.
TIMESTAMP also affected by different TIME ZONE related setting. DATETIME is constant.
TIMESTAMP internally converted a current time zone to UTC for storage, and during retrieval convert the back to the current time zone. DATETIME can not do this.
TIMESTAMP is 4 bytes and DATETIME is 8 bytes.
TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59'
Also...
When using kill -3 one should see the thread dump in the standard output. Most of the application servers write the standard output to a separate file. You should find it there when using kill -3. There are multiple ways of getting thread dumps:
kill -3 <PID>
: Gives output to standard output.For hotspot VM's we can also use jstack
command to generate a thread dump. It’s a part of the JDK. Syntax is as follows:
Usage:
jstack [-l] <pid> (to connect to running process)
jstack -F [-m] [-l] <pid>(to connect to a hung process)
- For JRockit JVM we can use JRCMD command which comes with JDK Syntax:
jrcmd <jrockit pid> [<command> [<arguments>]] [-l] [-f file] [-p] -h]
This will give you a list.
List<Card> cardsList = Arrays.asList(hand);
If you want an arraylist, you can do
ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));
Does your console app require user interaction? If so, that's a serious no-no and you should redesign your application. While there are some hacks to make this sort of work in older versions of the OS, this is guaranteed to break in the future.
If your app does not require user interaction, then perhaps your problem is related to the user the service is running as. Try making sure that you run as the correct user, or that the user and/or resources you are using have the right permissions.
If you require some kind of user-interaction, then you will need to create a client application and communicate with the service and/or sub-application via rpc, sockets, or named pipes.
Well if you want to return your array from a function you must make sure that the values are not stored on the stack as they will be gone when you leave the function.
So either make your array static or allocate the memory (or pass it in but your initial attempt is with a void parameter). For your method I would define it like this:
int *gnabber(){
static int foo[] = {1,2,3}
return foo;
}
You need to type result
to an array of string const result: string[] = [];
.
Yes. There are two kinds of types in .NET: reference types and value types.
References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.
Value types (e.g. int) by default do not have a concept of null. However, there is a wrapper for them called Nullable. This enables you to encapsulate the non-nullable value type and include null information.
The usage is slightly different, though.
// Both of these types mean the same thing, the ? is just C# shorthand.
private void Example(int? arg1, Nullable<int> arg2)
{
if (arg1.HasValue)
DoSomething();
arg1 = null; // Valid.
arg1 = 123; // Also valid.
DoSomethingWithInt(arg1); // NOT valid!
DoSomethingWithInt(arg1.Value); // Valid.
}
I was getting that behind a corporate proxy.
Solved by:
git config http.sslVerify "false"
I resolved error copying the files class.phpmailer.php , class.smtp.php to the folder where the file is PHPMailerAutoload.php, of course there should be the file that we will use to send the email.
The 64base method works for large images as well, I use that method to embed all the images into my website, and it works every time. I've done with files up to 2Mb size, jpg and png.
I have Notepad++ v6.8.8
Find: [([a-zA-Z])]
Replace: [\'\1\']
Will produce: $array[XYZ] => $array['XYZ']
If you want to overwrite the previous line (rather than continually adding to it), you can combine \r
with print(),
at the end of the print statement. For example,
from time import sleep
for i in xrange(0, 10):
print("\r{0}".format(i)),
sleep(.5)
print("...DONE!")
will count 0 to 9, replacing the old number in the console. The "...DONE!"
will print on the same line as the last counter, 9.
In your case for the OP, this would allow the console to display percent complete of the install as a "progress bar", where you can define a begin and end character position, and update the markers in between.
print("Installing |XXXXXX | 30%"),
If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.
https://developer.apple.com/reference/foundation/userdefaults
A default object must be a property list—that is, an instance of (or for collections, a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.
Here's a thread safe way of doing it:
// Foo.h
@interface Foo {
}
+(NSDictionary*) dictionary;
// Foo.m
+(NSDictionary*) dictionary
{
static NSDictionary* fooDict = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
// create dict
});
return fooDict;
}
These edits ensure that fooDict is only created once.
From Apple documentation: "dispatch_once - Executes a block object once and only once for the lifetime of an application."
in my case I had to change line ending from CRLF
to LF
for the run.sh
file and the error was gone.
I hope this helps,
Kirsten
This is what I do which seems to work quite well:
Date.prototype.addMinutes = function(minutes) {
var copiedDate = new Date(this.getTime());
return new Date(copiedDate.getTime() + minutes * 60000);
}
Then you can just call this like this:
var now = new Date();
console.log(now.addMinutes(50));
$('#id span').text()
is the answer!
You can use the converse approach to achieve the same result - start from the composite and then remove styling using the unset
keyword. For example, if you start with the following sample composition:
.composite {
color: red;
margin-left: 50px;
background-color: green
}
you can then increase selector specificity to selectively remove styles using unset
:
.composite.no-color {
color: unset
}
.composite.no-margin-left {
margin-left: unset
}
.composite.no-background-color {
background-color: unset
}
Here is a JSFiddle demonstrating this approach.
One benefit of this approach is that because the specificity
of the compound selectors is higher than the composite itself, you do not need all of the combinations of classes to achieve the desired results for multiple combinations:
/* Multi-unset compound selector combinations, such as the one that follows, ARE NOT NECESSARY because of the higher specificity of each individual compound selectors listed above. This keeps things simple. */
.composite.no-background-color.no-color.no-margin-left {
background-color: unset;
color: unset;
margin-left: unset
}
Furthermore, at 96% support for the unset
keyword, browser coverage is excellent.
Solved for me by running a docker desktop app, check-in notification. Setup if necessary.
$ net start com.docker.service
The Docker for Windows Service service is starting. The Docker for Windows Service service was started successfully.
$ docker version
$ net start com.docker.service
The requested service has already been started.
I suggest to use a container for each img
p
like this:
<div class="image123">
<div style="float:left;margin-right:5px;">
<img src="/images/tv.gif" height="200" width="200" />
<p style="text-align:center;">This is image 1</p>
</div>
<div style="float:left;margin-right:5px;">
<img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
<p style="text-align:center;">This is image 2</p>
</div>
<div style="float:left;margin-right:5px;">
<img src="/images/tv.gif/" height="200" width="200" />
<p style="text-align:center;">This is image 3</p>
</div>
</div>
Then apply float:left
to each container. I add and 5px
margin right
so there is a space between each image. Also alway close your elements. Maybe in html img
tag is not important to close but in XHTML is.
Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:
html
<div class="image123">
<div>
<img src="/images/tv.gif" />
<p>This is image 1</p>
</div>
<div>
<img class="middle-img" src="/images/tv.gif/" />
<p>This is image 2</p>
</div>
<div>
<img src="/images/tv.gif/" />
<p>This is image 3</p>
</div>
</div>
css
div{
float:left;
margin-right:5px;
}
div > img{
height:200px;
width:200px;
}
p{
text-align:center;
}
It's generally recommended that you use linked style sheets because:
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Hello");
list.add("World");
Map<String, List<String>> collect = list.stream()
.collect(Collectors.groupingBy(o -> o));
collect.entrySet()
.forEach(e -> System.out.println(e.getKey() + " - " + e.getValue().size()));
Necromancing:
It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:
;WITH baseTable AS
(
SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr
FROM baseTable
)
SELECT
RM
,ADR
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2
-- Not supported
--,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu
FROM CTE
Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.
I personally think that it's more important for the code to be readable and editable than performant. Whichever one you find easier to look at and it should be the one you choose for above factors. You can write it as:
$('#box').append(
$('<div/>')
.attr("id", "newDiv1")
.addClass("newDiv purple bloated")
.append("<span/>")
.text("hello world")
);
And your first Method as:
// create an element with an object literal, defining properties
var $e = $("<div>", {id: "newDiv1", name: 'test', class: "aClass"});
$e.click(function(){ /* ... */ });
// add the element to the body
$("#box").append($e);
But as far as readability goes; the jQuery approach is my favorite. Follow this Helpful jQuery Tricks, Notes, and Best Practices
I recently ran into the similar issue with react-native application. iPhone OS version was 13.1 I uninstalled the application and tried to install the app and noticed both location and notification permissions were not prompted.
On checking the settings, I could see my application was enabled for location(from previous installation) however there was no corresponding entry against the notification Tried uninstalling and rebooting without setting the time, it didn't work. Btw, I also tried to download the Appstore app, still same behavior.
The issue was resolved only after setting the device time.
pp does the job too, no gem requiring is required.
@a = Accrual.first ; pp @a
#<Accrual:0x007ff521e5ba50
id: 4,
year: 2018,
Jan: #<BigDecimal:7ff521e58f08,'0.11E2',9(27)>,
Feb: #<BigDecimal:7ff521e585d0,'0.88E2',9(27)>,
Mar: #<BigDecimal:7ff521e58030,'0.0',9(27)>,
Apr: #<BigDecimal:7ff521e53698,'0.88E2',9(27)>,
May: #<BigDecimal:7ff521e52fb8,'0.8E1',9(27)>,
June: #<BigDecimal:7ff521e52900,'0.8E1',9(27)>,
July: #<BigDecimal:7ff521e51ff0,'0.8E1',9(27)>,
Aug: #<BigDecimal:7ff521e51bb8,'0.88E2',9(27)>,
Sep: #<BigDecimal:7ff521e512f8,'0.88E2',9(27)>,
Oct: #<BigDecimal:7ff521e506c8,'0.0',9(27)>,
Nov: #<BigDecimal:7ff521e43d38,'0.888E3',9(27)>,
Dec: #<BigDecimal:7ff521e43478,'0.0',9(27)>,
You can also print two instances of an object:
pp( Accrual.first , Accrual.second)
`
`
`
Use the standard CSS Font Loading API.
Wait for (all) the fonts to load, and then show your content:
document.fonts.ready.then((fontFaceSet) => {
console.log(fontFaceSet.size, 'FontFaces loaded.');
document.getElementById('waitScreen').style.display = 'none';
});
When speaking with remote machines, Ansible by default assumes you are using SSH keys. SSH keys are encouraged but password authentication can also be used where needed by supplying the option --ask-pass. If using sudo features and when sudo requires a password, also supply --ask-become-pass (previously --ask-sudo-pass which has been deprecated).
Never used the feature but the docs say you can.
Since your content-type is application/x-www-form-urlencoded
you'll need to encode the POST body, especially if it contains characters like &
which have special meaning in a form.
Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.
Here are a couple links for reference.
function parseVideo(url) {
// - Supported YouTube URL formats:
// - http://www.youtube.com/watch?v=My2FRPA3Gf8
// - http://youtu.be/My2FRPA3Gf8
// - https://youtube.googleapis.com/v/My2FRPA3Gf8
// - Supported Vimeo URL formats:
// - http://vimeo.com/25451551
// - http://player.vimeo.com/video/25451551
// - Also supports relative URLs:
// - //player.vimeo.com/video/25451551
url.match(/(http:|https:|)\/\/(player.|www.)?(vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com))\/(video\/|embed\/|watch\?v=|v\/)?([A-Za-z0-9._%-]*)(\&\S+)?/);
if (RegExp.$3.indexOf('youtu') > -1) {
var type = 'youtube';
} else if (RegExp.$3.indexOf('vimeo') > -1) {
var type = 'vimeo';
}
return {
type: type,
id: RegExp.$6
};
}
function getVideoThumbnail(url, cb) {
var videoObj = parseVideo(url);
if (videoObj.type == 'youtube') {
cb('//img.youtube.com/vi/' + videoObj.id + '/maxresdefault.jpg');
} else if (videoObj.type == 'vimeo') {
$.get('http://vimeo.com/api/v2/video/' + videoObj.id + '.json', function(data) {
cb(data[0].thumbnail_large);
});
}
}
below solution works for me
.iml
filesIf you only want to upgrade one specific package called somepackage
, the command you should use in recent versions of pip is
pip install --upgrade --upgrade-strategy only-if-needed somepackage
This is very useful when you develop an application in Django that currently will only work with a specific version of Django (say Django=1.9.x) and want to upgrade some dependent package with a bug-fix/new feature and the upgraded package depends on Django (but it works with, say, any version of Django after 1.5).
The default behavior of pip install --upgrade django-some-package
would be to upgrade Django to the latest version available which could otherwise break your application, though with the --upgrade-strategy only-if-needed
dependent packages will now only be upgraded as necessary.
The drawback of Contains
method is that it doesn't allow to specify comparison type which is often important when comparing strings. It is always culture-sensitive and case-sensitive. So I think the answer of WhoIsRich is valuable, I just want to show a simpler alternative:
listOfStrings.Any(s => s.Equals(myString, StringComparison.OrdinalIgnoreCase))
In my case, the same error had a much easier fix. Basically my function was in a .js file that was not included in the current aspx that was showing. All I needed was the include line.
A lot contributions on this thread already, just summarize a sequence diagram to illustrate it in another way.
The is also a good link about this topic, https://web.stanford.edu/~ouster/cgi-bin/cs142-fall10/lecture.php?topic=cookie
Just an addition to the previous answers. Let's not forget that when dealing with real data there might be null values, so it's useful to also include those in the counting by using the option dropna=False
(default is True
)
An example:
>>> df['Embarked'].value_counts(dropna=False)
S 644
C 168
Q 77
NaN 2
var val = yyy.First().Value;
return yyy.All(x=>x.Value == val) ? val : otherValue;
Cleanest way I can think of. You can make it a one-liner by inlining val, but First() would be evaluated n times, doubling execution time.
To incorporate the "empty set" behavior specified in the comments, you simply add one more line before the two above:
if(yyy == null || !yyy.Any()) return otherValue;
Have a look at <openssl/pem.h>
. It gives possible BEGIN markers.
Copying the content from the above link for quick reference:
#define PEM_STRING_X509_OLD "X509 CERTIFICATE"
#define PEM_STRING_X509 "CERTIFICATE"
#define PEM_STRING_X509_PAIR "CERTIFICATE PAIR"
#define PEM_STRING_X509_TRUSTED "TRUSTED CERTIFICATE"
#define PEM_STRING_X509_REQ_OLD "NEW CERTIFICATE REQUEST"
#define PEM_STRING_X509_REQ "CERTIFICATE REQUEST"
#define PEM_STRING_X509_CRL "X509 CRL"
#define PEM_STRING_EVP_PKEY "ANY PRIVATE KEY"
#define PEM_STRING_PUBLIC "PUBLIC KEY"
#define PEM_STRING_RSA "RSA PRIVATE KEY"
#define PEM_STRING_RSA_PUBLIC "RSA PUBLIC KEY"
#define PEM_STRING_DSA "DSA PRIVATE KEY"
#define PEM_STRING_DSA_PUBLIC "DSA PUBLIC KEY"
#define PEM_STRING_PKCS7 "PKCS7"
#define PEM_STRING_PKCS7_SIGNED "PKCS #7 SIGNED DATA"
#define PEM_STRING_PKCS8 "ENCRYPTED PRIVATE KEY"
#define PEM_STRING_PKCS8INF "PRIVATE KEY"
#define PEM_STRING_DHPARAMS "DH PARAMETERS"
#define PEM_STRING_DHXPARAMS "X9.42 DH PARAMETERS"
#define PEM_STRING_SSL_SESSION "SSL SESSION PARAMETERS"
#define PEM_STRING_DSAPARAMS "DSA PARAMETERS"
#define PEM_STRING_ECDSA_PUBLIC "ECDSA PUBLIC KEY"
#define PEM_STRING_ECPARAMETERS "EC PARAMETERS"
#define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY"
#define PEM_STRING_PARAMETERS "PARAMETERS"
#define PEM_STRING_CMS "CMS"
The new for-each
loop is just a short hand for the older loop. The new loop is easier to use for arrays and some iterators, but not as flexible, so the old loop has to be using in some situations, like counting from 0 to 9.
>>> info = lambda data: len(data)>10 and data[:10]+'...' or data
>>> info('sdfsdfsdfsdfsdfsdfsdfsdfsdfsdfsdf')
'sdfsdfsdfs...'
>>> info('sdfsdf')
'sdfsdf'
>>>
Do Cmd+F12+Fn Key on mac in IntelliJ if clicking Cmd+F12 starts.
If you don't mind using jQuery, then you can use offset()
function. Refer to documentation if you want to read up more about this function.
There is better solution for Oracle instead of using dbms_random.value, while it requires full scan to order rows by dbms_random.value and it is quite slow for large tables.
Use this instead:
SELECT *
FROM employee sample(1)
WHERE rownum=1
I had the same issue and I found this.
On the url, it requires the server key in the end and not the api key for the app.
So Basically, you just add the server key in the end of the URL like this:
Now, to obtain the server key, just follow these steps:
1) Go to Developer Console https://code.google.com/apis/console/
2) In the Credentials, under Public API Access, Create New key
3) Select the server key from the option.
4) Enter your IP Address on the field and if you have more ip addresses, you can just add on every single line.NOTE: Enter the IP Address only when you want to use it for your testing purpose. Else leave the IP Address section blank.
5) Once you are done, click create and your new Server Key will be generated and you can then add that server key to your URL.
Last thing is that, instead of putting the sensor=true in the middle of the URL, you can add it in the end like this:
This will definitely solve the issue and just remember to use the server key for Places API
.
EDIT
I believe the web URL has changed in the past years. You can access developers console from here now - https://console.developers.google.com/apis/dashboard
Hope this answer will help you and other viewers. Good Luck .. :)
You can also use includes
const isApple = ['iPhone', 'iPad', 'iPod', 'iPad Simulator', 'iPhone Simulator', 'iPod Simulator',].includes(navigator.platform)
MKMapView
extension based on this answer (+ floating-point zoom level accuracy):
import Foundation
import MapKit
extension MKMapView {
var zoomLevel: Double {
get {
return log2(360 * (Double(self.frame.size.width / 256) / self.region.span.longitudeDelta)) + 1
}
set (newZoomLevel){
setCenterCoordinate(coordinate:self.centerCoordinate, zoomLevel: newZoomLevel, animated: false)
}
}
private func setCenterCoordinate(coordinate: CLLocationCoordinate2D, zoomLevel: Double, animated: Bool) {
let span = MKCoordinateSpan(latitudeDelta: 0, longitudeDelta: 360 / pow(2, zoomLevel) * Double(self.frame.size.width) / 256)
setRegion(MKCoordinateRegion(center: coordinate, span: span), animated: animated)
}
}
Why do you use new Date instead of a static UTC string?
function clearListCookies(){
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++){
var spcook = cookies[i].split("=");
document.cookie = spcook[0] + "=;expires=Thu, 21 Sep 1979 00:00:01 UTC;";
}
}
Try resetting your network settings
Settings -> General -> Reset -> Reset Network Settings
And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".
http://support.apple.com/kb/ts2529
This one worked for me.
I'm using this kind of routine for programmatically chaining animations.
final Animation anim_out = AnimationUtils.loadAnimation(context, android.R.anim.fade_out);
final Animation anim_in = AnimationUtils.loadAnimation(context, android.R.anim.fade_in);
anim_out.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation)
{
////////////////////////////////////////
// HERE YOU CHANGE YOUR IMAGE CONTENT //
////////////////////////////////////////
//ui_image.setImage...
anim_in.setAnimationListener(new AnimationListener()
{
@Override
public void onAnimationStart(Animation animation) {}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationEnd(Animation animation) {}
});
ui_image.startAnimation(anim_in);
}
});
ui_image.startAnimation(anim_out);
While the question mentions Chrome and Firefox, there are other software without cross domain security. I mention it for people who ignore that such software exists.
For example, PhantomJS is an engine for browser automation, it supports cross domain security deactivation.
phantomjs.exe --web-security=no script.js
See this other comment of mine: Userscript to bypass same-origin policy for accessing nested iframes
You can add a sequence of numbers very easily with
data$ID <- seq.int(nrow(data))
If you are already using library(tidyverse)
, you can use
data <- tibble::rowid_to_column(data, "ID")
You could convert it to an array and then print that out with Arrays.toString(Object[])
:
System.out.println(Arrays.toString(stack.toArray()));
Take a look at http://www.csharp-examples.net/download-files/ and msdn docs on webclient http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
My suggestion is try the synchronous download as its more straightforward. you might get ideas on whether webclient parameters are wrong or the file is in incorrect format while trying this.
Here is a code sample..
private void btnDownload_Click(object sender, EventArgs e)
{
string filepath = textBox1.Text;
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadFileAsync(new Uri("http://mysite.com/myfile.txt"), filepath);
}
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
Here is the code you need to ensure that only one instance is running. This is the method of using a named mutex.
public class Program
{
static System.Threading.Mutex singleton = new Mutex(true, "My App Name");
static void Main(string[] args)
{
if (!singleton.WaitOne(TimeSpan.Zero, true))
{
//there is already another instance running!
Application.Exit();
}
}
}
Logs rotate for a reason, so that you only keep so many log files around. In log4j.xml you can add this to your node:
<param name="MaxBackupIndex" value="20"/>
The value tells log4j.xml to only keep 20 rotated log files around. You can limit this to 5 if you want or even 1. If your application isn't logging that much data, and you have 20 log files spanning the last 8 months, but you only need a weeks worth of logs, then I think you need to tweak your log4j.xml "MaxBackupIndex" and "MaxFileSize" params.
Alternatively, if you are using a properties file (instead of the xml) and wish to save 15 files (for example)
log4j.appender.[appenderName].MaxBackupIndex = 15
The event is called beforeunload
, so you can assign a function to window.onbeforeunload
.
I had the same problem on ios7. I called it in selector and it worked on both ios7 and ios8.
[self performSelector: @selector(showMainView) withObject: nil afterDelay: 0.0];
- (void) showMainView {
HomeViewController * homeview = [
[HomeViewController alloc] initWithNibName: @
"HomeViewController"
bundle: nil];
UINavigationController * navcont = [
[UINavigationController alloc] initWithRootViewController: homeview];
navcont.navigationBar.tintColor = [UIColor whiteColor];
navcont.navigationBar.barTintColor = App_Theme_Color;
[navcont.navigationBar
setTitleTextAttributes: @ {
NSForegroundColorAttributeName: [UIColor whiteColor]
}];
navcont.modalPresentationStyle = UIModalPresentationFullScreen;
navcont.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self.navigationController presentViewController: navcont animated: YES completion: ^ {
}];
}
I had the same problem, my code is below:
private Connection conn = DriverManager.getConnection(Constant.MYSQL_URL, Constant.MYSQL_USER, Constant.MYSQL_PASSWORD);
private Statement stmt = conn.createStatement();
I have not loaded the driver class, but it works locally, I can query the results from MySQL, however, it does not work when I deploy it to Tomcat, and the errors below occur:
No suitable driver found for jdbc:mysql://172.16.41.54:3306/eduCloud
so I loaded the driver class, as below, when I saw other answers posted:
Class.forName("com.mysql.jdbc.Driver");
It works now! I don't know why it works well locally, I need your help, thank you so much!
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
Use "%~1"
. %~1
alone removes surrounding quotes. However since you can't know whether the input parameter %1
has quotes or not, you should ensure by "%~1"
that they are added for sure. This is especially helpful when concatenating variables, e.g. convert.exe "%~1.input" "%~1.output"
making a dynamycal width with mobile devices support
http://www.codeography.com/2011/06/14/dynamic-fixed-width-layout-with-css.html
GetValueOrDefault()
retrieves the value of the object. If it is null, it returns the default value of int , which is 0.
Example:
v2= v1.GetValueOrDefault();