You can set up the log level by using setLevel().
The levels are useful to easily set the kind of informations you want the program to display.
For example:
Logger.getRootLogger().setLevel(Level.WARN); //will not show debug messages
The set of possible levels are:
TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL
According to Logging Services manual
Client-side validation was not being executed at all on my web form and I had no idea why. It turns out the problem was the name of the javascript function was the same as the server control ID.
So you can't do this...
<script>
function vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="vld" />
But this works:
<script>
function validate_vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="validate_vld" />
I'm guessing it conflicts with internal .NET Javascript?
You've simply got it backwards. Specifying a minimum width would make the select menu always be at least that width, so it will continue expanding to 90% no matter what the window size is, also being at least the size of its longest option.
You need to use max-width
instead. This way, it will let the select menu expand to its longest option, but if that expands past your set maximum of 90% width, crunch it down to that width.
You can try these. 1. stringify your JSON Object before calling the server action via ajax 2. deserialize the string in the action then use the data as a dictionary.
Javascript sample below (sending the JSON Object
$.ajax(
{
type: 'POST',
url: 'TheAction',
data: { 'data': JSON.stringify(theJSONObject)
}
})
Action (C#) sample below
[HttpPost]
public JsonResult TheAction(string data) {
string _jsonObject = data.Replace(@"\", string.Empty);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
Dictionary<string, string> jsonObject = serializer.Deserialize<Dictionary<string, string>>(_jsonObject);
return Json(new object{status = true});
}
It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:
#define FOO(n) foo(n);bar(n)
and you do:
void foobar(int n) {
if (n)
FOO(n);
}
then this expands to:
void foobar(int n) {
if (n)
foo(n);bar(n);
}
Notice that the second call bar(n)
is not part of the if
statement anymore.
Wrap both into do { } while(0)
, and you can also use the macro in an if
statement.
So you have committed your local changes to your local repository. Then in order to get remote changes to your local repository without making changes to your local files, you can use git fetch
. Actually git pull
is a two step operation: a non-destructive git fetch
followed by a git merge
. See What is the difference between 'git pull' and 'git fetch'? for more discussion.
Detailed example:
Suppose your repository is like this (you've made changes test2
:
* ed0bcb2 - (HEAD, master) test2
* 4942854 - (origin/master, origin/HEAD) first
And the origin
repository is like this (someone else has committed test1
):
* 5437ca5 - (HEAD, master) test1
* 4942854 - first
At this point of time, git will complain and ask you to pull first if you try to push your test2
to remote repository. If you want to see what test1 is without modifying your local repository, run this:
$ git fetch
Your result local repository would be like this:
* ed0bcb2 - (HEAD, master) test2
| * 5437ca5 - (origin/master, origin/HEAD) test1
|/
* 4942854 - first
Now you have the remote changes in another branch, and you keep your local files intact.
Then what's next? You can do a git merge
, which will be the same effect as git pull
(when combined with the previous git fetch
), or, as I would prefer, do a git rebase origin/master
to apply your change on top of origin/master
, which gives you a cleaner history.
In C int foo()
and int foo(void)
are different functions. int foo()
accepts an arbitrary number of arguments, while int foo(void)
accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void
consistently when you mean no arguments.
If you have a variable a
, extern int a;
is a way to tell the compiler that a
is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern
, static
) only affects its visibility and extern
is the default, so extern
is actually unnecessary.
I suggest removing the extern
, it is extraneous and is usually omitted.
I had to create a table with both a fixed header and a fixed first column using pure CSS and none of the answers here were quite what I wanted.
The position: sticky
property supports both sticking to the top (as I've seen it used the most) and to the side in modern versions of Chrome, Firefox, and Edge. This can be combined with a div
that has the overflow: scroll
property to give you a table with fixed headers that can be placed anywhere on your page:
Place your table in a container:
<div class="container">
<table></table>
</div>
Use overflow: scroll
on your container to enable scrolling:
div.container {
overflow: scroll;
}
As Dagmar pointed out in the comments, the container also requires a max-width
and a max-height
.
Use position: sticky
to have table cells stick to the edge and top
, right
, or left
to choose which edge to stick to:
thead th {
position: -webkit-sticky; /* for Safari */
position: sticky;
top: 0;
}
tbody th {
position: -webkit-sticky; /* for Safari */
position: sticky;
left: 0;
}
As MarredCheese mentioned in the comments, if your first column contains <td>
elements instead of <th>
elements, you can use tbody td:first-child
in your CSS instead of tbody th
To have the header in the first column stick to the left, use:
thead th:first-child {
left: 0;
z-index: 1;
}
/* Use overflow:scroll on your container to enable scrolling: */
div {
max-width: 400px;
max-height: 150px;
overflow: scroll;
}
/* Use position: sticky to have it stick to the edge
* and top, right, or left to choose which edge to stick to: */
thead th {
position: -webkit-sticky; /* for Safari */
position: sticky;
top: 0;
}
tbody th {
position: -webkit-sticky; /* for Safari */
position: sticky;
left: 0;
}
/* To have the header in the first column stick to the left: */
thead th:first-child {
left: 0;
z-index: 2;
}
/* Just to display it nicely: */
thead th {
background: #000;
color: #FFF;
/* Ensure this stays above the emulated border right in tbody th {}: */
z-index: 1;
}
tbody th {
background: #FFF;
border-right: 1px solid #CCC;
/* Browsers tend to drop borders on sticky elements, so we emulate the border-right using a box-shadow to ensure it stays: */
box-shadow: 1px 0 0 0 #ccc;
}
table {
border-collapse: collapse;
}
td,
th {
padding: 0.5em;
}
_x000D_
<div>
<table>
<thead>
<tr>
<th></th>
<th>headheadhead</th>
<th>headheadhead</th>
<th>headheadhead</th>
<th>headheadhead</th>
<th>headheadhead</th>
<th>headheadhead</th>
<th>headheadhead</th>
</tr>
</thead>
<tbody>
<tr>
<th>head</th>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
</tr>
<tr>
<th>head</th>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
</tr>
<tr>
<th>head</th>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
</tr>
<tr>
<th>head</th>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
</tr>
<tr>
<th>head</th>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
</tr>
<tr>
<th>head</th>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
<td>body</td>
</tr>
</tbody>
</table>
</div>
_x000D_
delete from emp
where rowid not in
(select max(rowid) from emp group by empno);
delete from emp where rowid in
(
select rid from
(
select rowid rid,
row_number() over(partition by empno order by empno) rn
from emp
)
where rn > 1
);
delete from emp e1
where rowid not in
(select max(rowid) from emp e2
where e1.empno = e2.empno );
Make sure you're calling super()
as the first thing in your constructor.
You should set this
for setAuthorState
method
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
constructor(props) {
super(props);
this.handleAuthorChange = this.handleAuthorChange.bind(this);
}
handleAuthorChange(event) {
let {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
Another alternative based on arrow function
:
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
handleAuthorChange = (event) => {
const {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib
) <c:out>
tag or fn:escapeXml
function for this. E.g.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>
and
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">
That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).
If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. &
would become &amp;
instead of &
so that the enduser would literally see &
instead of &
in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.
VERY IMPORTANT Additional info on difference between .text() and .html():
If your selector selects more than one item, e.g you have two spans like so
<span class="foo">bar1</span>
<span class="foo">bar2</span>
,
then
$('.foo').text();
appends the two texts and give you that; whereas
$('.foo').html();
gives you only one of those.
#include <thread>
#include <iostream>
#include <vector>
using namespace std;
void doSomething(int id) {
cout << id << "\n";
}
/**
* Spawns n threads
*/
void spawnThreads(int n)
{
std::vector<thread> threads(n);
// spawn n threads:
for (int i = 0; i < n; i++) {
threads[i] = thread(doSomething, i + 1);
}
for (auto& th : threads) {
th.join();
}
}
int main()
{
spawnThreads(10);
}
Here's another example that was tested, and will match search & replace patterns:
import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
Example use:
replaceAll("/fooBar.txt","Hello\sWorld!$","Goodbye\sWorld.")
Here is a good article on the matter - "Use references when you can, and pointers when you have to."
ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"
Since PowerShell can call .NET classes, you could do the following:
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("somefilepath").FileVersion
Or as noted here on a list of files:
get-childitem * -include *.dll,*.exe | foreach-object { "{0}`t{1}" -f $_.Name, [System.Diagnostics.FileVersionInfo]::GetVersionInfo($_).FileVersion }
Or even nicer as a script: https://jtruher3.wordpress.com/2006/05/14/powershell-and-file-version-information/
Using javascript you can style the scroll bars. Which works fine in IE as well as FF.
Check the below links
From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques
Warning: this is an experimental feature that could dramatically change or even cease to exist in future releases
You can use ES7 statics:
npm install babel-preset-stage-0
And then add "stage-0"
to .babelrc presets:
{
"presets": ["es2015", "react", "stage-0"]
}
Afterwards, you go
class Component extends React.Component {
static foo = 'bar';
static baz = {a: 1, b: 2}
}
And then you use them like this:
Component.foo
I don't know how they are getting away with it, or what negative side effects their may be, but I'm using Hover.com to host some of my domains, and recently setup the apex of my domain as a CNAME there. Their DNS editing tool did not complain at all, and my domain happily resolves via the CNAME assigned.
Here is what Dig shows me for this domain (actual domain obfuscated as mydomain.com):
; <<>> DiG 9.8.3-P1 <<>> mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2056
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;mydomain.com. IN A
;; ANSWER SECTION:
mydomain.com. 394 IN CNAME myapp.parseapp.com.
myapp.parseapp.com. 300 IN CNAME parseapp.com.
parseapp.com. 60 IN A 54.243.93.102
if you got troubles with windows cmd command and .bat just escape percents like that
git show -s --format=%%ct
The % character has a special meaning for command line parameters and FOR parameters. To treat a percent as a regular character, double it: %%
touch ~/.gitignore
Example
# these work
*.gz
*.tmproj
*.7z
# these won't as they are folders
.vscode/
build/
# but you can do this
.vscode/*
build/*
git config --get core.excludesfile
git config --global core.excludesfile '~/.gitignore'
Voila!!
After messing around with @BringBackCommodore64 answer I figured it out
[link](file:///d:/absolute.md) # absolute filesystem path
[link](./relative1.md) # relative to opened file
[link](/relativeToProject.md) # relative to opened project
All of them tested in Visual Studio Code
and working,
Note: The absolute path works in editor but doesn't work in markdown preview mode!
sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename
sudo update-rc.d filename defaults
Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln
).
At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename
) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*
. Updated above code to reflect this.
Also as pointed out in the comments (by Charles Brandt), /filename
must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.
Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts
As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.
According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering
", in which case you have to pass sequence and runlevel configuration through command line arguments.
The equivalent argument set for the above example is
sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .
Look at jQuery Toggle
HTML:
<div id='content'>Hello World</div>
<input type='button' id='hideshow' value='hide/show'>
jQuery:
jQuery(document).ready(function(){
jQuery('#hideshow').live('click', function(event) {
jQuery('#content').toggle('show');
});
});
For versions of jQuery 1.7 and newer use
jQuery(document).ready(function(){
jQuery('#hideshow').on('click', function(event) {
jQuery('#content').toggle('show');
});
});
For reference, kindly check this demo
Try the to_date function.
For myself, this problem was caused by using the prettier
VSCode plugin without having a prettier config file in the workspace.
Disabling the plugin fixed the problem. It could have also probably been fixed by relying on the prettier config.
Read the file $AS/standalone/deployments/README.txt
for the autodeploy mode : This is done via the "auto-deploy" attributes on the deployment-scanner element in the standalone.xml configuration file:
<deployment-scanner scan-interval="5000" relative-to="jboss.server.base.dir"
path="deployments" auto-deploy-zipped="true" **auto-deploy-exploded="true"**/>
High resolution is relative... I was looking at the examples and they mostly cater for milliseconds. However for me it is important to measure microseconds. I have not seen a platform independant solution for microseconds and thought something like the code below will be usefull. I was timing on windows only for the time being and will most likely add a gettimeofday() implementation when doing the same on AIX/Linux.
#ifdef WIN32
#ifndef PERFTIME
#include <windows.h>
#include <winbase.h>
#define PERFTIME_INIT unsigned __int64 freq; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq); unsigned __int64 startTime; unsigned __int64 endTime; double timeDifferenceInMilliseconds;
#define PERFTIME_START QueryPerformanceCounter((LARGE_INTEGER *)&startTime);
#define PERFTIME_END QueryPerformanceCounter((LARGE_INTEGER *)&endTime); timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency); printf("Timing %fms\n",timeDifferenceInMilliseconds);
#define PERFTIME(funct) {unsigned __int64 freq; QueryPerformanceFrequency((LARGE_INTEGER*)&freq); double timerFrequency = (1.0/freq); unsigned __int64 startTime; QueryPerformanceCounter((LARGE_INTEGER *)&startTime); unsigned __int64 endTime; funct; QueryPerformanceCounter((LARGE_INTEGER *)&endTime); double timeDifferenceInMilliseconds = ((endTime-startTime) * timerFrequency); printf("Timing %fms\n",timeDifferenceInMilliseconds);}
#endif
#else
//AIX/Linux gettimeofday() implementation here
#endif
Usage:
PERFTIME(ProcessIntenseFunction());
or
PERFTIME_INIT
PERFTIME_START
ProcessIntenseFunction()
PERFTIME_END
It's not possible to decrypt MD5
hash which created. You need all information to decrypt the MD5
value which was used during encryption.
You can use AES
algorithm to encrypt and decrypt
JavaScript AES encryption and decryption (Advanced Encryption Standard)
The ASP.NET Web API has replaced the WCF Web API previously mentioned.
I thought I'd post an updated answer since most of these responses are from early 2012, and this thread is one of the top results when doing a Google search for "call restful service C#".
Current guidance from Microsoft is to use the Microsoft ASP.NET Web API Client Libraries to consume a RESTful service. This is available as a NuGet package, Microsoft.AspNet.WebApi.Client. You will need to add this NuGet package to your solution.
Here's how your example would look when implemented using the ASP.NET Web API Client Library:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ConsoleProgram
{
public class DataObject
{
public string Name { get; set; }
}
public class Class1
{
private const string URL = "https://sub.domain.com/objects.json";
private string urlParameters = "?api_key=123";
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
// List data response.
HttpResponseMessage response = client.GetAsync(urlParameters).Result; // Blocking call! Program will wait here until a response is received or a timeout occurs.
if (response.IsSuccessStatusCode)
{
// Parse the response body.
var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result; //Make sure to add a reference to System.Net.Http.Formatting.dll
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.Name);
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
// Make any other calls using HttpClient here.
// Dispose once all HttpClient calls are complete. This is not necessary if the containing object will be disposed of; for example in this case the HttpClient instance will be disposed automatically when the application terminates so the following call is superfluous.
client.Dispose();
}
}
}
If you plan on making multiple requests, you should re-use your HttpClient instance. See this question and its answers for more details on why a using statement was not used on the HttpClient instance in this case: Do HttpClient and HttpClientHandler have to be disposed between requests?
For more details, including other examples, see Call a Web API From a .NET Client (C#)
This blog post may also be useful: Using HttpClient to Consume ASP.NET Web API REST Services
Update: If you are using Angular 1.2+, use ng-repeat-start. See @jmagnusson's answer.
Otherwise, how about putting the ng-repeat on tbody? (AFAIK, it is okay to have multiple <tbody>s in a single table.)
<tbody ng-repeat="row in array">
<tr ng-repeat="item in row">
<td>{{item}}</td>
</tr>
</tbody>
_tmain is a macro that gets redefined depending on whether or not you compile with Unicode or ASCII. It is a Microsoft extension and isn't guaranteed to work on any other compilers.
The correct declaration is
int _tmain(int argc, _TCHAR *argv[])
If the macro UNICODE is defined, that expands to
int wmain(int argc, wchar_t *argv[])
Otherwise it expands to
int main(int argc, char *argv[])
Your definition goes for a bit of each, and (if you have UNICODE defined) will expand to
int wmain(int argc, char *argv[])
which is just plain wrong.
std::cout works with ASCII characters. You need std::wcout if you are using wide characters.
try something like this
#include <iostream>
#include <tchar.h>
#if defined(UNICODE)
#define _tcout std::wcout
#else
#define _tcout std::cout
#endif
int _tmain(int argc, _TCHAR *argv[])
{
_tcout << _T("There are ") << argc << _T(" arguments:") << std::endl;
// Loop through each argument and print its number and value
for (int i=0; i<argc; i++)
_tcout << i << _T(" ") << argv[i] << std::endl;
return 0;
}
Or you could just decide in advance whether to use wide or narrow characters. :-)
Updated 12 Nov 2013:
Changed the traditional "TCHAR" to "_TCHAR" which seems to be the latest fashion. Both work fine.
End Update
there is a simple way to do this: in the html file add:
<link rel="stylesheet" href="fonts/vermin_vibes.ttf" />
Note: you put the name of .ttf file you have. then go to to your css file and add:
h1 {
color: blue;
font-family: vermin vibes;
}
Note: you put the font family name of the font you have.
Note: do not write the font-family name as your font.ttf name example: if your font.ttf name is: "vermin_vibes.ttf" your font-family will be: "vermin vibes" font family doesn't contain special chars as "-,_"...etc it only can contain spaces.
Simply put these codes at top of your PHP/index file:
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL
ini_set('ignore_repeated_errors', TRUE); // always use TRUE
ini_set('display_errors', FALSE); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment
ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'your/path/to/errors.log'); // Logging file path
Most of the times these terms Web Server and Application server are used interchangeably.
Following are some of the key differences in features of Web Server and Application Server:
Example of such configuration is Apache Tomcat HTTP Server and Oracle (formerly BEA) WebLogic Server. Apache Tomcat HTTP Server is Web Server and Oracle WebLogic is Application Server.
In some cases the servers are tightly integrated such as IIS and .NET Runtime. IIS is web server. When equipped with .NET runtime environment, IIS is capable of providing application services.
SELECT COUNT(1) FROM service s WHERE s.service_id = ?
git fetch origin our-team
or
git pull origin our-team
but first you should make sure that you already on the branch you want to update to (featurex).
Use the set method to replace the old value with a new one.
list.set( 2, "New" );
-w
is the GCC-wide option to disable warning messages.
I had faced similar issue on IE10. I had a workaround by using the jQuery ajax request to retrieve data:
$.ajax({
url: YOUR_XML_FILE
aync: false,
success: function (data) {
// Store data into a variable
},
dataType: YOUR_DATA_TYPE,
complete: ON_COMPLETE_FUNCTION_CALL
});
string foo = "Apple, Plum, Cherry";
string[] myArr = null;
myArr = foo.Split(',');
I think you need to set symbreaks = FALSE
That should allow for asymmetrical color scales.
# ------------- SCRIPT ------------- #
#!/bin/bash
echo
echo "# arguments called with ----> ${@} "
echo "# \$1 ----------------------> $1 "
echo "# \$2 ----------------------> $2 "
echo "# path to me ---------------> ${0} "
echo "# parent path --------------> ${0%/*} "
echo "# my name ------------------> ${0##*/} "
echo
exit
# ------------- CALLED ------------- #
# Notice on the next line, the first argument is called within double,
# and single quotes, since it contains two words
$ /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"
# ------------- RESULTS ------------- #
# arguments called with ---> 'hello there' 'william'
# $1 ----------------------> 'hello there'
# $2 ----------------------> 'william'
# path to me --------------> /misc/shell_scripts/check_root/show_parms.sh
# parent path -------------> /misc/shell_scripts/check_root
# my name -----------------> show_parms.sh
# ------------- END ------------- #
You can hide an image using javascript like this:
document.images['imageName'].style.visibility = hidden;
If that isn't what you are after, you need to explain yourself more clearly.
Note: this only answers part of the question.
If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:
SQL> show parameter sessions
This gives you an output like:
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
java_max_sessionspace_size integer 0
java_soft_sessionspace_limit integer 0
license_max_sessions integer 0
license_sessions_warning integer 0
sessions integer 248
shared_server_sessions integer
The sessions parameter is the one what you want.
Right click on the res folder and add your image as Image Assets in this way. Android studio will automatically generate image assets with different resolutions.
You can directly create the folder and drag image inside but you won't have the different sized icons if you do that.
Here's how I did it:
@fake-command /u %1 /p %2
Here's what the command looks like:
test.cmd admin P@55w0rd > test-log.txt
The %1
applies to the first parameter the %2
(and here's the tricky part) applies to the second. You can have up to 9 parameters passed in this way.
This question was asked some time ago, but people's thinking moves on.
Section 6.5.3 in this draft (authored by Fielding and Reschke) gives status code 403 a slightly different meaning to the one documented in RFC 2616.
It reflects what happens in authentication & authorization schemes employed by a number of popular web-servers and frameworks.
I've emphasized the bit I think is most salient.
6.5.3. 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
An origin server that wishes to "hide" the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).
Whatever convention you use, the important thing is to provide uniformity across your site / API.
R = HexToR("#FFFFFF");
G = HexToG("#FFFFFF");
B = HexToB("#FFFFFF");
function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
Use these Function to achive the result without any issue. :)
Congrats to the previous answers... But I realised if the icons are in a row (say three icons as represented in the image above), you need to play around with columns and rows.
Here is the code
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
FlatButton(
onPressed: () {},
child: Icon(
Icons.call,
)),
FlatButton(
onPressed: () {},
child: Icon(
Icons.message,
)),
FlatButton(
onPressed: () {},
child: Icon(
Icons.block,
color: Colors.red,
)),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text(
' Call',
),
Text(
'Message',
),
Text(
'Block',
style: TextStyle(letterSpacing: 2.0, color: Colors.red),
),
],
),
],
),
Go to C:\wamp\alias
. Open the file phpmyadmin.conf
and change
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
to
<Directory "c:/wamp/apps/phpmyadmin3.5.1/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Allow,Deny
Allow from all
</Directory>
problem solved
In case you want to see the local variables of a calling function use select-frame
before info locals
E.g.:
(gdb) bt
#0 0xfec3c0b5 in _lwp_kill () from /lib/libc.so.1
#1 0xfec36f39 in thr_kill () from /lib/libc.so.1
#2 0xfebe3603 in raise () from /lib/libc.so.1
#3 0xfebc2961 in abort () from /lib/libc.so.1
#4 0xfebc2bef in _assert_c99 () from /lib/libc.so.1
#5 0x08053260 in main (argc=1, argv=0x8047958) at ber.c:480
(gdb) info locals
No symbol table info available.
(gdb) select-frame 5
(gdb) info locals
i = 28
(gdb)
The way via unlist
and matrix
seems a bit convoluted, and requires you to hard-code the number of elements (this is actually a pretty big no-go. Of course you could circumvent hard-coding that number and determine it at run-time)
I would go a different route, and construct a data frame directly from the list that strsplit
returns. For me, this is conceptually simpler. There are essentially two ways of doing this:
as.data.frame
– but since the list is exactly the wrong way round (we have a list of rows rather than a list of columns) we have to transpose the result. We also clear the rownames
since they are ugly by default (but that’s strictly unnecessary!):
`rownames<-`(t(as.data.frame(strsplit(text, '\\.'))), NULL)
Alternatively, use rbind
to construct a data frame from the list of rows. We use do.call
to call rbind
with all the rows as separate arguments:
do.call(rbind, strsplit(text, '\\.'))
Both ways yield the same result:
[,1] [,2] [,3] [,4]
[1,] "F" "US" "CLE" "V13"
[2,] "F" "US" "CA6" "U13"
[3,] "F" "US" "CA6" "U13"
[4,] "F" "US" "CA6" "U13"
[5,] "F" "US" "CA6" "U13"
[6,] "F" "US" "CA6" "U13"
…
Clearly, the second way is much simpler than the first.
If you're checking for explicit types, why are you declaring those variables as T
's?
T HowToCast<T>(T t)
{
if (typeof(T) == typeof(string))
{
var newT1 = "some text";
var newT2 = t; //this builds but I'm not sure what it does under the hood.
var newT3 = t.ToString(); //for sure the string you want.
}
return t;
}
android.os.NetworkOnMainThreadException is thrown when network operations are performed on the main thread. You better do this in AsyncTask to remove this Exception. Write it this way:
new AsyncTask<Void,String,String>(){
@Override
protected Void doInBackground(Void... params) {
// Perform your network operation.
// Get JSON or XML string from the server.
// Store in a local variable (say response) and return.
return response;
}
protected void onPostExecute(String results){
// Response returned by doInBackGround() will be received
// by onPostExecute(String results).
// Now manipulate your jason/xml String(results).
}
}.execute();
}
Not going to be everyone's fix, but it was for me:
So, i ran across this exact issue. The problem I seemed to have was when my DataTable didnt have an ID column, but the target destination had one with a primary key.
When i adapted my DataTable to have an id, the copy worked perfectly.
In my scenario, the Id column isnt very important to have the primary key so i deleted this column from the target destination table and the SqlBulkCopy is working without issue.
Actual SETUP:
Install the x64 JDK
, and try the back-next option first, and then try setting JAVA_HOME
like the error message says, but if that doesn't work for you either, then try this:
Do as it says, set JAVA_HOME
in your environment variables, but in the path use forward slashes instead of backslashes.
Seriously.
For me it failed when JAVA_HOME
was C:\Program Files\Java\jdk1.6.0_31
but worked fine when it was C:/Program Files/Java/jdk1.6.0_31
- drove me nuts!
If this is not enough, also add to the beginning of the Environment Variable Path
%JAVA_HOME%;
Updated values in System Environment Variables:
JAVA_HOME=C:/Program Files/Java/jdk1.8.0_11
JRE_HOME=C:/Program Files/Java/jre8
Path=%JAVA_HOME%;C:...
either:
df['index1'] = df.index
or, .reset_index
:
df.reset_index(level=0, inplace=True)
so, if you have a multi-index frame with 3 levels of index, like:
>>> df
val
tick tag obs
2016-02-26 C 2 0.0139
2016-02-27 A 2 0.5577
2016-02-28 C 6 0.0303
and you want to convert the 1st (tick
) and 3rd (obs
) levels in the index into columns, you would do:
>>> df.reset_index(level=['tick', 'obs'])
tick obs val
tag
C 2016-02-26 2 0.0139
A 2016-02-27 2 0.5577
C 2016-02-28 6 0.0303
As in this answer to a similar question, there is no need to hack settings. It is much simpler to write:
print(foo.to_string())
This error comes when you are trying to load jasper report file with the extension .jasper
For Example
c://reports//EmployeeReport.jasper"
While you should load jasper report file with the extension .jrxml
For Example
c://reports//EmployeeReport.jrxml"
[See Problem Screenshot ][1] [1]: https://i.stack.imgur.com/D5SzR.png
[See Solution Screenshot][2] [2]: https://i.stack.imgur.com/VeQb9.png
It seems you're actually talking about an MVC (Model-View-Controller) pattern, where logic is separated into various "tiers". Django, as a framework, follows MVC (loosely). You have models that contain your business logic and relate directly to tables in your database, views which in effect act like the controller, handling requests and returning responses, and finally, templates which handle presentation.
Django isn't just one of these, it is a complete framework for application development and provides all the tools you need for that purpose.
Frontend vs Backend is all semantics. You could potentially build a Django app that is entirely "backend", using its built-in admin contrib package to manage the data for an entirely separate application. Or, you could use it solely for "frontend", just using its views and templates but using something else entirely to manage the data. Most usually, it's used for both. The built-in admin (the "backend"), provides an easy way to manage your data and you build apps within Django to present that data in various ways. However, if you were so inclined, you could also create your own "backend" in Django. You're not forced to use the default admin.
Use <div class="row">
and <div class="form-group col-xs-6">
Here a fiddle :https://jsfiddle.net/core972/SMkZV/2/
None of the above worked for me. My app was working fine in previous than Lollipop. But when I tested it on Lollipop the above error came up. It refused to install. I didn't have any previous versions installed so all the above solutions are invalid in my case. But thanks to this SO solution now it is running fine. Just like most developers I followed Google's misleading tutorial and I added the permissions by copy and paste like this:
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<permission android:name="com.google.android.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
This would work with older versions < Lollipop. So now I changed to:
<uses-permission android:name="com.mycompany.myappname.c2dm.permission.RECEIVE" />
<permission android:name="com.mycompany.myappname.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
This is an older question, but I came up with a solution I thought others might like.
def get_current_datetime_as_dict():
n = datetime.now()
t = n.timetuple()
field_names = ["year",
"month",
"day",
"hour",
"min",
"sec",
"weekday",
"md",
"yd"]
return dict(zip(field_names, t))
timetuple() can be zipped with another array, which creates labeled tuples. Cast that to a dictionary and the resultant product can be consumed with get_current_datetime_as_dict()['year']
.
This has a little more overhead than some of the other solutions on here, but I've found it's so nice to be able to access named values for clartiy's sake in the code.
The accepted answer made radio button disappear on Chrome. This works:
input:not([type="radio"]):not([type="checkbox"]) {
-webkit-appearance: none;
border-radius: 0;
}
I would like to add, that yes. While using the NAT adapter settings in Vmware and turning off windows firewall I was able to ping other guest machines in my test environment.
Sidenote: Best practice would be to implement a hardware firewall in larger environments and turn off windows firewall on the Domain Controller.
if you want to use it in all of your classes you can use:
public var yourVariable = "something"
if you want to use just in one class you can use :
var yourVariable = "something"
The list.append
function does not return any value(but None
), it just adds the value to the list you are using to call that method.
In the first loop round you will assign None
(because the no-return of append
) to a
, then in the second round it will try to call a.append
, as a is None
it will raise the Exception you are seeing
You just need to change it to:
a=[]
for i in range(5):
a.append(i)
print(a)
# [0, 1, 2, 3, 4]
list.append
is what is called a mutating or destructive method, i.e. it will destroy or mutate the previous object into a new one(or a new state).
If you would like to create a new list based in one list without destroying or mutating it you can do something like this:
a=['a', 'b', 'c']
result = a + ['d']
print result
# ['a', 'b', 'c', 'd']
print a
# ['a', 'b', 'c']
As a corollary only, you can mimic the append
method by doing the following:
a=['a', 'b', 'c']
a = a + ['d']
print a
# ['a', 'b', 'c', 'd']
Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy
file (path is as in the reply of Petey B)
permission java.io.FilePermission "your folder path", "write"
In your case it would be
permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"
Here /-
means any files or sub-folders inside this folder.
Warning: But by doing this, you are inviting some security risk.
Suppose provided array is inPutArray = [1,2,5,8,7,3] expected O/P -> 7 (second largest)
take temp array
temp = [0,0], int dummmy=0;
for (no in inPutArray) {
if(temp[1]<no)
temp[1] = no
if(temp[0]<temp[1]){
dummmy = temp[0]
temp[0] = temp[1]
temp[1] = temp
}
}
print("Second largest no is %d",temp[1])
To print all the ascii values from 0 to 255 using while loop.
#include<stdio.h>
int main(void)
{
int a;
a = 0;
while (a <= 255)
{
printf("%d = %c\n", a, a);
a++;
}
return 0;
}
There is no way to do this in C. There are a lot of different approaches. Typically the simplest is to define a set of constants that represent your strings and do a look up by string on to get the constant:
#define BADKEY -1
#define A1 1
#define A2 2
#define B1 3
#define B2 4
typedef struct { char *key; int val; } t_symstruct;
static t_symstruct lookuptable[] = {
{ "A1", A1 }, { "A2", A2 }, { "B1", B1 }, { "B2", B2 }
};
#define NKEYS (sizeof(lookuptable)/sizeof(t_symstruct))
int keyfromstring(char *key)
{
int i;
for (i=0; i < NKEYS; i++) {
t_symstruct *sym = lookuptable[i];
if (strcmp(sym->key, key) == 0)
return sym->val;
}
return BADKEY;
}
/* ... */
switch (keyfromstring(somestring)) {
case A1: /* ... */ break;
case A2: /* ... */ break;
case B1: /* ... */ break;
case B2: /* ... */ break;
case BADKEY: /* handle failed lookup */
}
There are, of course, more efficient ways to do this. If you keep your keys sorted, you can use a binary search. You could use a hashtable too. These things change your performance at the expense of maintenance.
You've got several options how to do this, either:
urlencode()
or rawurlencode()
- functions designed to encode URLs for http protocolstr_replace()
- "heavy machinery" string replacestrtr()
- would have better performance than str_replace()
when replacing multiple characterspreg_replace()
use regular expressions (perl compatible)strtr()
Assuming that you want to replace "\t"
and " "
with "%20"
:
$replace_pairs = array(
"\t" => '%20',
" " => '%20',
);
return strtr( $text, $replace_pairs)
preg_replace()
You've got few options here, either replacing just space ~ ~
, again replacing space and tab ~[ \t]~
or all kinds of spaces ~\s~
:
return preg_replace( '~\s~', '%20', $text);
Or when you need to replace string like this "\t \t \t \t"
with just one %20
:
return preg_replace( '~\s+~', '%20', $text);
I assumed that you really want to use manual string replacement and handle more types of whitespaces such as non breakable space (
)
For any file path with space, simply put them in double quotations will work in Windows Powershell. For example, if you want to go to Program Files directory, instead of use
PS C:\> cd Program Files
which will induce error, simply use the following will solve the problem:
PS C:\> cd "Program Files"
The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready()
then it should work perfectly well:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").show("slow");
});
});
An alternative is to place the <script></script>
at the foot of the page, so it's encountered after the DOM has been loaded and ready.
To make the div
hide again, once the #music
element is clicked, simply use toggle()
:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").toggle();
});
});
And for fading:
$(document).ready(
function(){
$("#music").click(function () {
$("#musicinfo").fadeToggle();
});
});
I don't understand the issue. But here is the thing that solved my issue.
Go to Excel Options > Save > Save Files in this format > Select "Excel Workbook(*.xlsx)". Previously, my WorkBooks were opening in [Compatibuility Mode] And now they are opening in normal mode. Range function works fine with that.
start cmd /k
did the magic for me. I actually used it for preparing cordova phonegap app it runs the command, shows the result and waits for the user to close it. Below is the simple example
start cmd /k echo Hello, World!
What I did use in my case
start cmd /k cordova prepare
Update
You could even have a title for this by using
start "My Title" echo Hello, World!
Andrew's answer is good.
And just to help you out a bit more, here's how you use multiple formatting in one string
"Hello %s, my name is %s" % ('john', 'mike') # Hello john, my name is mike".
If you are using ints instead of string, use %d instead of %s.
"My name is %s and i'm %d" % ('john', 12) #My name is john and i'm 12
I have worked out this simple example
import numpy as np
ar = np.array([3,4,5,14,2,4,3,7])
print [X for X in list(ar) if (X >= 3 and X <= 6)]
>>>
[3, 4, 5, 4, 3]
on the last line, don't use $(this).remove()
use $(this).hide()
instead.
EDIT: To clarify,on the close click event you're removing the #terms
div from the DOM which is why its not coming back. You just need to hide it instead.
Try setLenient(false)
.
Addendum: It looks like you're recognizing variously formatted Date
strings. If you have to do entry, you might like looking at this example that extends InputVerifier
.
I think easy way to disable button is :data => { disable_with: "Saving.." }
This will submit a form and then make a button disable, Also it won't disable button if you have any validations like required = 'required'.
By default, the classes in the csv
module use Windows-style line terminators (\r\n
) rather than Unix-style (\n
). Could this be what’s causing the apparent double line breaks?
If so, you can override it in the DictWriter
constructor:
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)
Bootstrap 4 has a class named text-nowrap
. It is just what you need.
Another way is using set data type.
Some characteristic of Sets: Sets are unordered, can include mixed data types, elements in a set cannot be repeated, are mutable.
Solving your question:
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
sorted(set(df.A))
The answer in List type:
[1, 2, 3, 6, 8]
With strtok(), it can be done in just one line: "if (strtok(s," \t")==NULL)". For example:
#include <stdio.h>
#include <string.h>
int is_whitespace(char *s) {
if (strtok(s," \t")==NULL) {
return 1;
} else {
return 0;
}
}
void demo(void) {
char s1[128];
char s2[128];
strcpy(s1," abc \t ");
strcpy(s2," \t ");
printf("s1 = \"%s\"\n", s1);
printf("s2 = \"%s\"\n", s2);
printf("is_whitespace(s1)=%d\n",is_whitespace(s1));
printf("is_whitespace(s2)=%d\n",is_whitespace(s2));
}
int main() {
char url[63] = {'\0'};
do {
printf("Enter a URL: ");
scanf("%s", url);
printf("url='%s'\n", url);
} while (is_whitespace(url));
return 0;
}
The file that I was using was saved through Powershell in UTF-8 format. I changed it to ANSI and it fixed the problem.
INNER JOIN: Returns all rows when there is at least one match in BOTH tables
LEFT JOIN: Return all rows from the left table, and the matched rows from the right table
RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.testpoc.controller"/>
<bean id="ViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="ViewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
OneToOneField (one-to-one) realizes, in object orientation, the notion of composition, while ForeignKey (one-to-many) relates to agregation.
On Windows 8.1 I had to run cmd.exe as administrator (even though I was logged in as admin). Otherwise I got an error when trying to execute: httpd.exe -k uninstall
Error: C:\Program Files\Apache\bin>(OS 5)Access is denied. : AH00373: Apache2.4: OpenS ervice failed
I prefer this approach because it's more general-purpose, i.e. you can use it on a file, on the result of f.readlines()
, on a StringIO
object, whatever:
def read_specific_lines(file, lines_to_read):
"""file is any iterable; lines_to_read is an iterable containing int values"""
lines = set(lines_to_read)
last = max(lines)
for n, line in enumerate(file):
if n + 1 in lines:
yield line
if n + 1 > last:
return
>>> with open(r'c:\temp\words.txt') as f:
[s for s in read_specific_lines(f, [1, 2, 3, 1000])]
['A\n', 'a\n', 'aa\n', 'accordant\n']
for Python > 3.4
from urllib import parse
url = 'http://foo.appspot.com/abc?def=ghi'
query_def=parse.parse_qs(parse.urlparse(url).query)['def'][0]
You would want to amend the commit and then do a force push which will update the branch with the PR.
Here's how I recommend you do this:
git reset --soft HEAD^
or if it's a different commit, you would want to replace 'HEAD^' with the commit id)git commit -a -c ORIG_HEAD
The now that your branch has been updated, the Pull Request will include your changes.
Here's a link to Gits documentation where they have a pretty good example under Undo a commit and redo.
Here is the code I use when I want to preload images before appending them to the page.
It is also important to check if the image is already loaded from the cache (for IE).
//create image to preload:
var imgPreload = new Image();
$(imgPreload).attr({
src: photoUrl
});
//check if the image is already loaded (cached):
if (imgPreload.complete || imgPreload.readyState === 4) {
//image loaded:
//your code here to insert image into page
} else {
//go fetch the image:
$(imgPreload).load(function (response, status, xhr) {
if (status == 'error') {
//image could not be loaded:
} else {
//image loaded:
//your code here to insert image into page
}
});
}
Use FOR XML PATH('')
- which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result
SELECT STUFF((SELECT ',' + INSTITUTIONNAME
FROM EDUCATION EE
WHERE EE.STUDENTNUMBER=E.STUDENTNUMBER
ORDER BY sortOrder
FOR XML PATH('')), 1, 1, '') AS listStr
FROM EDUCATION E
GROUP BY E.STUDENTNUMBER
Here is the FIDDLE
Using Java 8 APIs,
List<Long> empNoList = Arrays.asList(1234, 7678, 2432, 9756556, 3354646);
List<String> parameters = new ArrayList<>();
empNoList.forEach(empNo -> parameters.add("?")); //Use forEach to add required no. of '?'
String commaSepParameters = String.join(",", parameters); //Use String to join '?' with ','
StringBuilder selectQuery = new StringBuilder().append("SELECT COUNT(EMP_ID) FROM EMPLOYEE WHERE EMP_ID IN (").append(commaSepParameters).append(")");
You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet");
by DocumentElement
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope); //call the eb service Method
} catch (Exception e) {
e.printStackTrace();
} //Next task is to get Response and format that response
SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");
for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
{
obj3 = (SoapObject) obj2.getProperty(i);
obj3.getProperty(0).toString(); //value of column 1
obj3.getProperty(1).toString(); //value of column 2
//like that you will get value from each column
}
If you have any problem regarding this you can write me..
This happened to me earlier (didn't have access to an EC2 instance someone else created but had access to AWS web console) and I blogged the answer: http://readystate4.com/2013/04/09/aws-gaining-ssh-access-to-an-ec2-instance-you-lost-access-to/
Basically, you can detached the EBS drive, attach it to an EC2 that you do have access to. Add your SSH pub key to ~ec2-user/.ssh/authorized_keys
on this attached drive. Then put it back on the old EC2 instance. step-by-step in the link using Amazon AMI.
No need to make snapshots or create a new cloned instance.
Here's a way to get the list of people a user is following with just a browser and some copy-paste (A pure javascript solution based on Deep Seeker's answer):
Get the user's id (In a browser, navigate to https://www.instagram.com/user_name/?__a=1 and look for response -> graphql -> user -> id [from Deep Seeker's answer])
Open another browser window
Open the browser console and paste this in it
options = {
userId: your_user_id,
list: 1 //1 for following, 2 for followers
}
_x000D_
change to your user id and hit enter
paste this in the console and hit enter
`https://www.instagram.com/graphql/query/?query_hash=c76146de99bb02f6415203be841dd25a&variables=` + encodeURIComponent(JSON.stringify({
"id": options.userId,
"include_reel": true,
"fetch_mutual": true,
"first": 50
}))
_x000D_
Navigate to the outputted link
(This sets up the headers for the http request. If you try to run the script on a page where this isn't open, it won't work.)
let config = {
followers: {
hash: 'c76146de99bb02f6415203be841dd25a',
path: 'edge_followed_by'
},
following: {
hash: 'd04b0a864b4b54837c0d870b0e77e076',
path: 'edge_follow'
}
};
var allUsers = [];
function getUsernames(data) {
var userBatch = data.map(element => element.node.username);
allUsers.push(...userBatch);
}
async function makeNextRequest(nextCurser, listConfig) {
var params = {
"id": options.userId,
"include_reel": true,
"fetch_mutual": true,
"first": 50
};
if (nextCurser) {
params.after = nextCurser;
}
var requestUrl = `https://www.instagram.com/graphql/query/?query_hash=` + listConfig.hash + `&variables=` + encodeURIComponent(JSON.stringify(params));
var xhr = new XMLHttpRequest();
xhr.onload = function(e) {
var res = JSON.parse(xhr.response);
var userData = res.data.user[listConfig.path].edges;
getUsernames(userData);
var curser = "";
try {
curser = res.data.user[listConfig.path].page_info.end_cursor;
} catch {
}
var users = [];
if (curser) {
makeNextRequest(curser, listConfig);
} else {
var printString =""
allUsers.forEach(item => printString = printString + item + "\n");
console.log(printString);
}
}
xhr.open("GET", requestUrl);
xhr.send();
}
if (options.list === 1) {
console.log('following');
makeNextRequest("", config.following);
} else if (options.list === 2) {
console.log('followers');
makeNextRequest("", config.followers);
}
_x000D_
After a few seconds it should output the list of users your user is following.
None of the answers so far gets at the problem of filenames with spaces.
Additionally, all that use xargs
are subject to fail if the total length of paths in the tree exceeds the shell environment size limit (defaults to a few megabytes in Linux).
Here is one that fixes these problems in a pretty direct manner. The subshell takes care of files with spaces. The awk
totals the stream of individual file wc
outputs, so it ought never to run out of space. It also restricts the exec
to files only (skipping directories):
find . -type f -name '*.php' -exec bash -c 'wc -l "$0"' {} \; | awk '{s+=$1} END {print s}'
This is more of a warning than an answer.
Having seen in the other answers my_list = [None] * 10
, I was tempted and set up an array like this speakers = [['','']] * 10
and came to regret it immensely as the resulting list
did not behave as I thought it should.
I resorted to:
speakers = []
for i in range(10):
speakers.append(['',''])
As [['','']] * 10
appears to create an list
where subsequent elements are a copy of the first element.
for example:
>>> n=[['','']]*10
>>> n
[['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
>>> n[0][0] = "abc"
>>> n
[['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', ''], ['abc', '']]
>>> n[0][1] = "True"
>>> n
[['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True'], ['abc', 'True']]
Whereas with the .append
option:
>>> n=[]
>>> for i in range(10):
... n.append(['',''])
...
>>> n
[['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
>>> n[0][0] = "abc"
>>> n
[['abc', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
>>> n[0][1] = "True"
>>> n
[['abc', 'True'], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', ''], ['', '']]
I'm sure that the accepted answer by ninjagecko does attempt to mention this, sadly I was too thick to understand.
Wrapping up, take care!
From the jQuery documentation:
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().
Additionally to the PIL
image check you can also add file name extension check like this:
filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))
Note that this only checks if the file name has a valid image extension, it does not actually open the image to see if it's a valid image, that's why you need to use additionally PIL
or one of the libraries suggested in the other answers.
$excel = new PHPExcel();
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="your_name.xls"');
header('Cache-Control: max-age=0');
// Do your stuff here
$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
// This line will force the file to download
$writer->save('php://output');
I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
Also, name it divrat.m
, not divrat.M
. This shouldn't matter on most OSes, but who knows...
You can also test whether matlab can find a function by using the which
command, i.e.
which divrat
I wrote this a few years ago (run it with administrator rights):
<#
.SYNOPSIS
Change the registry key in order that double-clicking on a file with .PS1 extension
start its execution with PowerShell.
.DESCRIPTION
This operation bring (partly) .PS1 files to the level of .VBS as far as execution
through Explorer.exe is concern.
This operation is not advised by Microsoft.
.NOTES
File Name : ModifyExplorer.ps1
Author : J.P. Blanc - [email protected]
Prerequisite: PowerShell V2 on Vista and later versions.
Copyright 2010 - Jean Paul Blanc/Silogix
.LINK
Script posted on:
http://www.silogix.fr
.EXAMPLE
PS C:\silogix> Set-PowAsDefault -On
Call Powershell for .PS1 files.
Done!
.EXAMPLE
PS C:\silogix> Set-PowAsDefault
Tries to go back
Done!
#>
function Set-PowAsDefault
{
[CmdletBinding()]
Param
(
[Parameter(mandatory=$false, ValueFromPipeline=$false)]
[Alias("Active")]
[switch]
[bool]$On
)
begin
{
if ($On.IsPresent)
{
Write-Host "Call PowerShell for .PS1 files."
}
else
{
Write-Host "Try to go back."
}
}
Process
{
# Text Menu
[string]$TexteMenu = "Go inside PowerShell"
# Text of the program to create
[string] $TexteCommande = "%systemroot%\system32\WindowsPowerShell\v1.0\powershell.exe -Command ""&'%1'"""
# Key to create
[String] $clefAModifier = "HKLM:\SOFTWARE\Classes\Microsoft.PowerShellScript.1\Shell\Open\Command"
try
{
$oldCmdKey = $null
$oldCmdKey = Get-Item $clefAModifier -ErrorAction SilentlyContinue
$oldCmdValue = $oldCmdKey.getvalue("")
if ($oldCmdValue -ne $null)
{
if ($On.IsPresent)
{
$slxOldValue = $null
$slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
if ($slxOldValue -eq $null)
{
New-ItemProperty $clefAModifier -Name "slxOldValue" -Value $oldCmdValue -PropertyType "String" | Out-Null
New-ItemProperty $clefAModifier -Name "(default)" -Value $TexteCommande -PropertyType "ExpandString" | Out-Null
Write-Host "Done !"
}
else
{
Write-Host "Already done!"
}
}
else
{
$slxOldValue = $null
$slxOldValue = Get-ItemProperty $clefAModifier -Name "slxOldValue" -ErrorAction SilentlyContinue
if ($slxOldValue -ne $null)
{
New-ItemProperty $clefAModifier -Name "(default)" -Value $slxOldValue."slxOldValue" -PropertyType "String" | Out-Null
Remove-ItemProperty $clefAModifier -Name "slxOldValue"
Write-Host "Done!"
}
else
{
Write-Host "No former value!"
}
}
}
}
catch
{
$_.exception.message
}
}
end {}
}
Works in SQL server
Declare @GivenDate datetime
SET @GivenDate = GETDATE()
Select DATEADD(MM,DATEDIFF(MM, 0, @GivenDate),0) --First day of the month
Select DATEADD(MM,DATEDIFF(MM, -1, @GivenDate),-1) --Last day of the month
You could use HTML's indeterminate
IDL attribute on input
elements.
This might work for you:
printf "{new\nto\nlinux}" | paste -sd' '
{new to linux}
or:
printf "{new\nto\nlinux}" | tr '\n' ' '
{new to linux}
or:
printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}
If you just want to remove the header you can use a shortened version of lukiffer's answer:
using System.Web;
namespace Site
{
public sealed class HideServerHeaderModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.PreSendRequestHeaders +=
(sender, e) => HttpContext.Current.Response.Headers.Remove("Server");
}
}
}
And then in Web.config
:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="CustomHeaderModule" type="Site.HideServerHeaderModule" />
</modules>
</system.webServer>
Sometimes you need to first update the apt repo list.
sudo apt-get update
sudo apt purge python2.7-minimal
I could get to your expected result just by doing this in mysql:
SELECT id, min(record_date), other_cols
FROM mytable
GROUP BY id
Does this work for you?
It's too late, however the best example, how to add pseudo element in jQuery style
$(document).ready(function(){_x000D_
$("a.dummy").css({"background":"#003d79","color":"#fff","padding": "5px 10px","border-radius": "3px","text-decoration":"none"});_x000D_
$("a.dummy").hover(function() {_x000D_
$(this).css("background-color","#0670c9")_x000D_
}).mouseout(function(){_x000D_
$(this).css({"background-color":"#003d79",});_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>_x000D_
<a class="dummy" href="javascript:void()">Just Link</a>
_x000D_
str = "count a character occurance"
List = list(str)
print (List)
Uniq = set(List)
print (Uniq)
for key in Uniq:
print (key, str.count(key))
The OP, MAW74656, originally posted this answer in the question body in response to the accepted answer, as explained in this comment:
I used this and wrote a public method to call the code and return the boolean.
The OP's answer:
Code Used:
public bool tablesAreTheSame(DataTable table1, DataTable table2) { DataTable dt; dt = getDifferentRecords(table1, table2); if (dt.Rows.Count == 0) return true; else return false; } //Found at http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html private DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable) { //Create Empty Table DataTable ResultDataTable = new DataTable("ResultDataTable"); //use a Dataset to make use of a DataRelation object using (DataSet ds = new DataSet()) { //Add tables ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() }); //Get Columns for DataRelation DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count]; for (int i = 0; i < firstColumns.Length; i++) { firstColumns[i] = ds.Tables[0].Columns[i]; } DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count]; for (int i = 0; i < secondColumns.Length; i++) { secondColumns[i] = ds.Tables[1].Columns[i]; } //Create DataRelation DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false); ds.Relations.Add(r1); DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false); ds.Relations.Add(r2); //Create columns for return table for (int i = 0; i < FirstDataTable.Columns.Count; i++) { ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType); } //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable. ResultDataTable.BeginLoadData(); foreach (DataRow parentrow in ds.Tables[0].Rows) { DataRow[] childrows = parentrow.GetChildRows(r1); if (childrows == null || childrows.Length == 0) ResultDataTable.LoadDataRow(parentrow.ItemArray, true); } //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable. foreach (DataRow parentrow in ds.Tables[1].Rows) { DataRow[] childrows = parentrow.GetChildRows(r2); if (childrows == null || childrows.Length == 0) ResultDataTable.LoadDataRow(parentrow.ItemArray, true); } ResultDataTable.EndLoadData(); } return ResultDataTable; }
The BufferedWriter class offers a newLine()
method. Using this will ensure platform independence.
This is a fast solution with a temporary object.
var records = [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }],_x000D_
empid = [1, 4, 5],_x000D_
object = {},_x000D_
result;_x000D_
_x000D_
records.forEach(function (a) {_x000D_
object[a.empid] = a;_x000D_
});_x000D_
_x000D_
result = empid.map(function (a) {_x000D_
return object[a];_x000D_
});_x000D_
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
_x000D_
a = "MandY"
alow = a.lower()
if "mandy" in alow:
print "true"
work around
two function:
def get_class_attr(Cls) -> []:
import re
return [a for a, v in Cls.__dict__.items()
if not re.match('<function.*?>', str(v))
and not (a.startswith('__') and a.endswith('__'))]
def get_class_attr_val(cls):
attr = get_class_attr(type(cls))
attr_dict = {}
for a in attr:
attr_dict[a] = getattr(cls, a)
return attr_dict
use:
>>> class MyClass:
a = "12"
b = "34"
def myfunc(self):
return self.a
>>> m = MyClass()
>>> get_class_attr_val(m)
{'a': '12', 'b': '34'}
By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.
So just set it to:
<style name="AppTheme" parent="android:Theme.Holo" />
There is a lot of confusion about IdentityDbContext, a quick search in Stackoverflow and you'll find these questions:
"
Why is Asp.Net Identity IdentityDbContext a Black-Box?
How can I change the table names when using Visual Studio 2013 AspNet Identity?
Merge MyDbContext with IdentityDbContext"
To answer to all of these questions we need to understand that IdentityDbContext is just a class inherited from DbContext.
Let's take a look at IdentityDbContext source:
/// <summary>
/// Base class for the Entity Framework database context used for identity.
/// </summary>
/// <typeparam name="TUser">The type of user objects.</typeparam>
/// <typeparam name="TRole">The type of role objects.</typeparam>
/// <typeparam name="TKey">The type of the primary key for users and roles.</typeparam>
/// <typeparam name="TUserClaim">The type of the user claim object.</typeparam>
/// <typeparam name="TUserRole">The type of the user role object.</typeparam>
/// <typeparam name="TUserLogin">The type of the user login object.</typeparam>
/// <typeparam name="TRoleClaim">The type of the role claim object.</typeparam>
/// <typeparam name="TUserToken">The type of the user token object.</typeparam>
public abstract class IdentityDbContext<TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken> : DbContext
where TUser : IdentityUser<TKey, TUserClaim, TUserRole, TUserLogin>
where TRole : IdentityRole<TKey, TUserRole, TRoleClaim>
where TKey : IEquatable<TKey>
where TUserClaim : IdentityUserClaim<TKey>
where TUserRole : IdentityUserRole<TKey>
where TUserLogin : IdentityUserLogin<TKey>
where TRoleClaim : IdentityRoleClaim<TKey>
where TUserToken : IdentityUserToken<TKey>
{
/// <summary>
/// Initializes a new instance of <see cref="IdentityDbContext"/>.
/// </summary>
/// <param name="options">The options to be used by a <see cref="DbContext"/>.</param>
public IdentityDbContext(DbContextOptions options) : base(options)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="IdentityDbContext" /> class.
/// </summary>
protected IdentityDbContext()
{ }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of Users.
/// </summary>
public DbSet<TUser> Users { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User claims.
/// </summary>
public DbSet<TUserClaim> UserClaims { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User logins.
/// </summary>
public DbSet<TUserLogin> UserLogins { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User roles.
/// </summary>
public DbSet<TUserRole> UserRoles { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of User tokens.
/// </summary>
public DbSet<TUserToken> UserTokens { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of roles.
/// </summary>
public DbSet<TRole> Roles { get; set; }
/// <summary>
/// Gets or sets the <see cref="DbSet{TEntity}"/> of role claims.
/// </summary>
public DbSet<TRoleClaim> RoleClaims { get; set; }
/// <summary>
/// Configures the schema needed for the identity framework.
/// </summary>
/// <param name="builder">
/// The builder being used to construct the model for this context.
/// </param>
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<TUser>(b =>
{
b.HasKey(u => u.Id);
b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique();
b.HasIndex(u => u.NormalizedEmail).HasName("EmailIndex");
b.ToTable("AspNetUsers");
b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken();
b.Property(u => u.UserName).HasMaxLength(256);
b.Property(u => u.NormalizedUserName).HasMaxLength(256);
b.Property(u => u.Email).HasMaxLength(256);
b.Property(u => u.NormalizedEmail).HasMaxLength(256);
b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
});
builder.Entity<TRole>(b =>
{
b.HasKey(r => r.Id);
b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken();
b.Property(u => u.Name).HasMaxLength(256);
b.Property(u => u.NormalizedName).HasMaxLength(256);
b.HasMany(r => r.Users).WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired();
});
builder.Entity<TUserClaim>(b =>
{
b.HasKey(uc => uc.Id);
b.ToTable("AspNetUserClaims");
});
builder.Entity<TRoleClaim>(b =>
{
b.HasKey(rc => rc.Id);
b.ToTable("AspNetRoleClaims");
});
builder.Entity<TUserRole>(b =>
{
b.HasKey(r => new { r.UserId, r.RoleId });
b.ToTable("AspNetUserRoles");
});
builder.Entity<TUserLogin>(b =>
{
b.HasKey(l => new { l.LoginProvider, l.ProviderKey });
b.ToTable("AspNetUserLogins");
});
builder.Entity<TUserToken>(b =>
{
b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name });
b.ToTable("AspNetUserTokens");
});
}
}
Based on the source code if we want to merge IdentityDbContext with our DbContext we have two options:
First Option:
Create a DbContext which inherits from IdentityDbContext and have access to the classes.
public class ApplicationDbContext
: IdentityDbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
// Add additional items here as needed
}
Extra Notes:
1) We can also change asp.net Identity default table names with the following solution:
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(): base("DefaultConnection")
{
}
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("user");
modelBuilder.Entity<ApplicationUser>().ToTable("user");
modelBuilder.Entity<IdentityRole>().ToTable("role");
modelBuilder.Entity<IdentityUserRole>().ToTable("userrole");
modelBuilder.Entity<IdentityUserClaim>().ToTable("userclaim");
modelBuilder.Entity<IdentityUserLogin>().ToTable("userlogin");
}
}
2) Furthermore we can extend each class and add any property to classes like 'IdentityUser', 'IdentityRole', ...
public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
public ApplicationRole()
{
this.Id = Guid.NewGuid().ToString();
}
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
// Add any custom Role properties/code here
}
// Must be expressed in terms of our custom types:
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole,
string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
// Add additional items here as needed
}
To save time we can use AspNet Identity 2.0 Extensible Project Template to extend all the classes.
Second Option:(Not recommended)
We actually don't have to inherit from IdentityDbContext if we write all the code ourselves.
So basically we can just inherit from DbContext and implement our customized version of "OnModelCreating(ModelBuilder builder)" from the IdentityDbContext source code
As mentioned above In the html in the same button, you can ask to close the current modal with data-dismiss and open a new modal directly with data-target:
<button class="btn btn-success" data-toggle="modal" data-target="#modalRegistration" data-dismiss="modal">Register</button>
But this will cause scroll-bar disappear and you will notice that if the second modal was longer that the first one
So the solution is to add the following style in the modal inline style :
Style = "overflow-y : scroll ; "
If I understood right, this is what you want
int drawableResourceId = this.getResources().getIdentifier("nameOfDrawable", "drawable", this.getPackageName());
Where "this" is an Activity, written just to clarify.
In case you want a String in strings.xml or an identifier of a UI element, substitute "drawable"
int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
I warn you, this way of obtaining identifiers is really slow, use only where needed.
Link to official documentation: Resources.getIdentifier(String name, String defType, String defPackage)
If you want to do it by ClassName you could do:
<script type="text/javascript">
function hideTd(className){
var elements;
if (document.getElementsByClassName)
{
elements = document.getElementsByClassName(className);
}
else
{
var elArray = [];
var tmp = document.getElementsByTagName(elements);
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
elements = elArray;
}
for(var i = 0, i < elements.length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
I had similar issue in with Xcode 7.3 and iOS 9.3.
Command failed due to signal: Segmentation fault: 11
Basic steps such as Clean (cmd+shift+k) code, Delete derived data and Quit Xcode didn't work.
There was some culprit in my code.
It was [txtUserName.text.characters.count = 0]
In your case Review your code and fix the culprit.
just one line code to get simple Date format :
SimpleDateFormat.getDateInstance().format(Date())
output : 18-May-2020
SimpleDateFormat.getDateTimeInstance().format(Date())
output : 18-May-2020 11:00:39 AM
SimpleDateFormat.getTimeInstance().format(Date())
output : 11:00:39 AM
Hope this answer is enough to get this Date and Time Format ... :)
Using Anaconda + Spyder (Python 3.7)
[code]
import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
print(soma)
sess = tf.compat.v1.Session()
with sess:
print(sess.run(soma))
[console]
import tensorflow as tf
valor1 = tf.constant(2)
valor2 = tf.constant(3)
type(valor1)
print(valor1)
soma=valor1+valor2
type(soma)
Tensor("Const_8:0", shape=(), dtype=int32)
Out[18]: tensorflow.python.framework.ops.Tensor
print(soma)
Tensor("add_4:0", shape=(), dtype=int32)
sess = tf.compat.v1.Session()
with sess:
print(sess.run(soma))
5
you can use setSeconds
method by getting seconds from today and just adding 10 seconds in it
var today = new Date();
today.setSeconds(today.getSeconds() + 10);
You can add 10 *1000 milliseconds to the new date:
var today = new Date();
today = new Date(today.getTime() + 1000*10);
You can use setTime
:
today.setTime(now.getTime() + 10000)
have you tried this?
-
name: Jack
age: 32
-
name: Claudia
age: 25
I get this: [{"name"=>"Jack", "age"=>32}, {"name"=>"Claudia", "age"=>25}]
(I use the YAML
Ruby class).
As an extension to what John said, if you want to extract the string representation and store it in a std::string
do this:
#include <sstream>
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace
std::stringstream
is located in the <sstream>
header.
a
and b
are just two references to the same Person object. They both essentially hold the address of the Person
.
There is a ICloneable interface, though relatively few classes support it. With this, you would write:
Person b = a.Clone();
Then, b would be an entirely separate Person
.
You could also implement a copy constructor:
public Person(Person src)
{
// ...
}
There is no built-in way to copy all the fields. You can do it through reflection, but there would be a performance penalty.
You can also use the PostAsJsonAsync() method available in HttpClient()
var requestObj= JsonConvert.SerializeObject(obj);_x000D_
HttpResponseMessage response = await client.PostAsJsonAsync($"endpoint",requestObj).ConfigureAwait(false);
_x000D_
If you're using MacPorts, the path is
/opt/local/share/java/gradle
You can use
(get-item $scriptPath).Directoryname
to get the string path or if you want the Directory type use:
(get-item $scriptPath).Directory
I have used graphviz ( https://www.graphviz.org/gallery ) together with LaTeX using dot command to generate graphs in PDF and includegraphics
to include those.
If graphviz produces what you are aiming at, this might be the best way to integrate: dot2tex: https://ctan.org/pkg/dot2tex?lang=en
If you are using AngularJS version 1.X you could use the $log service instead of using console.log directly.
Simple service for logging. Default implementation safely writes the message into the browser's console (if present).
https://docs.angularjs.org/api/ng/service/$log
So if you have something similar to
angular.module('logExample', [])
.controller('LogController', ['$scope', function($scope) {
console.log('Hello World!');
}]);
you can replace it with
angular.module('logExample', [])
.controller('LogController', ['$scope', '$log', function($scope, $log) {
$log.log('Hello World!');
}]);
Angular 2+ does not have any built-in log service.
An ES6 implementation based on biziclops great answer:
root = {_x000D_
text: "root",_x000D_
children: [{_x000D_
text: "c1",_x000D_
children: [{_x000D_
text: "c11"_x000D_
}, {_x000D_
text: "c12"_x000D_
}]_x000D_
}, {_x000D_
text: "c2",_x000D_
children: [{_x000D_
text: "c21"_x000D_
}, {_x000D_
text: "c22"_x000D_
}]_x000D_
}, ]_x000D_
}_x000D_
_x000D_
console.log("DFS:")_x000D_
DFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
console.log("BFS:")_x000D_
BFS(root, node => node.children, node => console.log(node.text));_x000D_
_x000D_
function BFS(root, getChildren, visit) {_x000D_
let nodesToVisit = [root];_x000D_
while (nodesToVisit.length > 0) {_x000D_
const currentNode = nodesToVisit.shift();_x000D_
nodesToVisit = [_x000D_
...nodesToVisit,_x000D_
...(getChildren(currentNode) || []),_x000D_
];_x000D_
visit(currentNode);_x000D_
}_x000D_
}_x000D_
_x000D_
function DFS(root, getChildren, visit) {_x000D_
let nodesToVisit = [root];_x000D_
while (nodesToVisit.length > 0) {_x000D_
const currentNode = nodesToVisit.shift();_x000D_
nodesToVisit = [_x000D_
...(getChildren(currentNode) || []),_x000D_
...nodesToVisit,_x000D_
];_x000D_
visit(currentNode);_x000D_
}_x000D_
}
_x000D_
You need DATE_ADD/DATE_SUB
:
AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
should work.
You can put the jQuery's Ajax setup in synchronous mode by calling
jQuery.ajaxSetup({async:false});
And then perform your Ajax calls using jQuery.get( ... );
Then just turning it on again once
jQuery.ajaxSetup({async:true});
I guess it works out the same thing as suggested by @Adam, but it might be helpful to someone that does want to reconfigure their jQuery.get()
or jQuery.post()
to the more elaborate jQuery.ajax()
syntax.
import urllib
def fetch_thing(url, params, method):
params = urllib.urlencode(params)
if method=='POST':
f = urllib.urlopen(url, params)
else:
f = urllib.urlopen(url+'?'+params)
return (f.read(), f.code)
content, response_code = fetch_thing(
'http://google.com/',
{'spam': 1, 'eggs': 2, 'bacon': 0},
'GET'
)
[Update]
Some of these answers are old. Today I would use the requests
module like the answer by robaple.
Note that java11 now offers a new HTTP api HttpClient, which supports fully asynchronous operation, using java's CompletableFuture.
It also supports a synchronous version, with calls like send, which is synchronous, and sendAsync, which is asynchronous.
Example of an async request (taken from the apidoc):
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/"))
.timeout(Duration.ofMinutes(2))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofFile(Paths.get("file.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
A safe version to convert an iterator to a pointer (exactly what that means regardless of the implications) and by safe I mean no worries about having to dereference the iterator and cause possible exceptions / errors due to end()
/ other situations
#include <iostream>
#include <vector>
#include <string.h>
int main()
{
std::vector<int> vec;
char itPtr[25];
long long itPtrDec;
std::vector<int>::iterator it = vec.begin();
memset(&itPtr, 0, 25);
sprintf(itPtr, "%llu", it);
itPtrDec = atoll(itPtr);
printf("it = 0x%X\n", itPtrDec);
vec.push_back(123);
it = vec.begin();
memset(&itPtr, 0, 25);
sprintf(itPtr, "%llu", it);
itPtrDec = atoll(itPtr);
printf("it = 0x%X\n", itPtrDec);
}
will print something like
it = 0x0
it = 0x2202E10
It's an incredibly hacky way to do it, but if you need it, it does the job. You will receive some compiler warnings which, if really bothering you, can be removed with #pragma
To answer the WHY in your question:
Because the equality operator can only be applied to simple variable types, such as float
s, int
s, or char
s, and not to more sophisticated types, such as structures or arrays.
To determine if two strings are equal, you must explicitly compare the two character strings character by character.
I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :) Try this:
Use the same connection string in your code too:
Good luck.
You can Use KeyPress instead of KeyUp or KeyDown its more efficient and here's how to handle
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
button1.PerformClick();
}
}
hope it works
File file = new File("C:/aaa/bbb/ccc/ddd/test.java");
File curentPath = new File(file.getParent());
//get current path "C:/aaa/bbb/ccc/ddd/"
String currentFolder= currentPath.getName().toString();
//get name of file to string "ddd"
if you need to append folder "ddd" by another path use;
String currentFolder= "/" + currentPath.getName().toString();
You just need to make sure that the containers you want to talk to each other are on the same network. Networks are a first-class docker construct, and not specific to compose.
# front/docker-compose.yml
version: '2'
services:
front:
...
networks:
- some-net
networks:
some-net:
driver: bridge
...
# api/docker-compose.yml
version: '2'
services:
api:
...
networks:
- front_some-net
networks:
front_some-net:
external: true
Note: Your app’s network is given a name based on the “project name”, which is based on the name of the directory it lives in, in this case a prefix
front_
was added
They can then talk to each other using the service name. From front
you can do ping api
and vice versa.
I know this question is outdated, but I was searching for a solution for that as well and Google lists this at the very top:
this.dir <- dirname(parent.frame(2)$ofile)
setwd(this.dir)
put that somewhere into the file (best would be the beginning, though), so that the wd is changed according to that file.
According to the comments, this might not necessarily work on every platform (Windows seems to work, Linux/Mac for some). Keep in mind that this solution is for 'sourcing' the files, not necessarily for running chunks in that file.
TRY THIS CODE
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("Please enter number only...");
e.Handled = true;
}
}
Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx
You are getting Floating point exception because Number % i
, when i
is 0
:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2
. Since i = 1
in Number % i
it always be equal to zero, since Number is a int.
I'm a bit late to the party here but I have done this without the need for windowing or using
WHERE x IN (...)
SELECT TOP 1
--select the value needed from t1
[col2]
FROM
(
SELECT TOP 2 --the Nth row, alter this to taste
UE2.[col1],
UE2.[col2],
UE2.[date],
UE2.[time],
UE2.[UID]
FROM
[table1] AS UE2
WHERE
UE2.[col1] = ID --this is a subquery
AND
UE2.[col2] IS NOT NULL
ORDER BY
UE2.[date] DESC, UE2.[time] DESC --sorting by date and time newest first
) AS t1
ORDER BY t1.[date] ASC, t1.[time] ASC --this reverses the order of the sort in t1
It seems to work fairly fast although to be fair I only have around 500 rows of data
This works in MSSQL
The mimetypes module in the standard library will determine/guess the MIME type from a file extension.
If users are uploading files the HTTP post will contain the MIME type of the file alongside the data. For example, Django makes this data available as an attribute of the UploadedFile object.
If you don't feel like importing anything, you can try:
raise SystemExit, 0
In your version rand() % 10000
will yield an integer between 0
and 9999
. Since RAND_MAX may be as little as 32767, and since this is not exactly divisible by 10000 and not large relative to 10000, there will be significant bias in the 'randomness' of the result, moreover, the maximum value will be 0.9999, not 1.0, and you have unnecessarily restricted your values to four decimal places.
It is simple arithmetic, a random number divided by the maximum possible random number will yield a number from 0 to 1 inclusive, while utilising the full resolution and distribution of the RNG
double r2()
{
return (double)rand() / (double)RAND_MAX ;
}
Use (double)rand() / (double)((unsigned)RAND_MAX + 1)
if exclusion of 1.0 was intentional.
1 See the list of devices/emulators currently available.
$ adb devices
List of devices attached
G7NZCJ015313309 device emulator-5554 device
9885b6454e46383744 device
2 Run backup on your device/emulator
$ adb -s emulator-5554 backup -f ~/Desktop/data.ab -noapk com.your_app_package.app;
3 Extract data.ab
$ dd if=data.ab bs=1 skip=24 | openssl zlib -d | tar -xvf -;
You will find the database in /db
folder
Here is the easiest solution.
There are a lot of environment special configurations needed if you are using Maven. So, if you start your program from maven, just run the mvnDebug
command instead of mvn
, it will take care of starting your app with remote debugging configurated. Now you can just attach a debugger on port 8000.
It'll take care of all the environment problems for you.
The syntax to disable an HTML input is as follows:
<input type="text" id="input_id" DISABLED />
If you don't know how many attributes need to be processed, you can use the variadic argument list token(...
) introduced in PHP 5.6 (see full documentation here).
Syntax:
function <functionName> ([<type> ]...<$paramName>) {}
For example:
function someVariadricFunc(...$arguments) {
foreach ($arguments as $arg) {
// do some stuff with $arg...
}
}
someVariadricFunc(); // an empty array going to be passed
someVariadricFunc('apple'); // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');
As you can see, this token basically turns all parameters to an array, which you can process in any way you like.
You can simply set the status code of the response to 200 like the following
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)
public static void main(String[] args) throws ParseException {
java.util.Date fecha = new java.util.Date("Mon Dec 15 00:00:00 CST 2014");
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date;
date = (Date)formatter.parse(fecha.toString());
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" +
(cal.get(Calendar.MONTH) + 1) +
"/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
}
Caesar's solution is the best in my opinion, but if you still insist to use the strcpy
function, then after you have your strings ready:
string a = "text";
string b = "image";
You can try either:
strcpy(a.data(), b.data());
or
strcpy(a.c_str(), b.c_str());
Just call either the data()
or c_str()
member functions of the std::string
class, to get the char*
pointer of the string object.
The strcpy()
function doesn't have overload to accept two std::string
objects as parameters.
It has only one overload to accept two char*
pointers as parameters.
Both data
and c_str
return what does strcpy()
want exactly.
The obj
directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin
directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.
You can change the actual directories used for both purposes within the project settings, if you like.
I did test it a while ago, with the result that a for
loop is much faster than a foreach
loop. The cause is simple, the foreach
loop first needs to instantiate an IEnumerator
for the collection.
In plain JavaScript, simply use response = readline()
after printing a prompt.
In Node.js, you'll need to use the readline module: const readline = require('readline')
As the message said, you should set permission as owner to your user. So you can use following:
ALTER AUTHORIZATION
ON DATABASE::[YourDBName]
TO [UserLogin];
Hope helpful! Leave comment if it's ok for you.
More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.
In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.
You pick what matters the most to you.
Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.
I searched around as well and probably some answers do fit for some situations,
my situation is Mysql 5.7 on a Ubuntu 18.04.2 LTS system:
(get root privileges)
$ sudo bash
(set up password for root db user + implement security in steps)
# mysql_secure_installation
(give access to the root user via password in stead of socket)
(+ edit: apparently you need to set the password again?)
(don't set it to 'mySecretPassword'!!!)
# mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
mysql> set password for 'root'@'localhost' = PASSWORD('mySecretPassword');
mysql> FLUSH PRIVILEGES;
mysql> exit;
# service mysql restart
Many thanks to zetacu (and erich) for this excellent answer (after searching a couple of hours...)
Enjoy :-D
S.
Edit (2020):
This method doesn't work anymore, see this question for future reference...
Just an update to the answer of @rafa.pereira.
Since ggplot2
is part of tidyverse
, it makes sense to use the convenient tidyverse functions to get rid of NAs.
library(tidyverse)
airquality %>%
drop_na(Ozone) %>%
ggplot(aes(x = Ozone))+
geom_bar(stat="bin")
Note that you can also use drop_na()
without columns specification; then all the rows with NAs in any column will be removed.
If someone is looking to sub out more than a comma I'm a fan of:
"1,200".chars.grep(/\d/).join.to_i
dunno about performance but, it is more flexible than a gsub
, ie:
"1-200".chars.grep(/\d/).join.to_i
For anybody who may stumble upon this. There is a recent (Dec 2013) Security Update from Microsoft Windows on Windows 7 that is preventing remote execution. See http://support.microsoft.com/kb/2893294/en-us
I uninstalled the Security Update by going to Control Panel\Programs\Programs and Features\Installed Updates
It worked right after that.
On Xamarin.Android, It works for me and need change layout
var layout = recyclerView.GetLayoutManager() as GridLayoutManager;
layout.SpanCount = GetItemPerRow(Context);
recyclerView.SetAdapter(null);
recyclerView.SetAdapter(adapter); //reset
Add a default constraint with the GETDATE() function as value.
ALTER TABLE myTable
ADD CONSTRAINT CONSTRAINT_NAME
DEFAULT GETDATE() FOR myColumn
In short, it is a scripting notation for passing data about. In some ways an alternative to XML, natively supporting basic data types, arrays and associative arrays (name-value pairs, called Objects because that is what they represent).
The syntax is that used in JavaScript and JSON itself stands for "JavaScript Object Notation". However it has become portable and is used in other languages too.
A useful link for detail is here:
In 12c you can make use of the fact that columns which are set from invisible to visible are displayed as the last column of the table: Tips and Tricks: Invisible Columns in Oracle Database 12c
Maybe that is the 'trick' @jeffrey-kemp was talking about in his comment, but the link there does not work anymore.
Example:
ALTER TABLE my_tab ADD (col_3 NUMBER(10));
ALTER TABLE my_tab MODIFY (
col_1 invisible,
col_2 invisible
);
ALTER TABLE my_tab MODIFY (
col_1 visible,
col_2 visible
);
Now col_3 would be displayed first in a SELECT * FROM my_tab
statement.
Note: This does not change the physical order of the columns on disk, but in most cases that is not what you want to do anyway. If you really want to change the physical order, you can use the DBMS_REDEFINITION package.
I tried all the solutions above and in addition, those in related answers as well. Solutions including but not limited to passing the blob manually to a HTMLInputElement's file property, calling all the readAs* methods on FileReader, using a File instance as second argument for a FormData.append call, trying to get the blob data as a string by getting the values at URL.createObjectURL(myBlob) which turned out nasty and crashed my machine.
Now, if you happen to attempt those or more and still find you're unable to upload your blob, it could mean the problem is server-side. In my case, my blob exceeded the http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize and post_max_size limit in PHP.INI so the file was leaving the front end form but getting rejected by the server. You could either increase this value directly in PHP.INI or via .htaccess
Use sort() method to sort the list as below:
List list = new ArrayList();
//add elements to the list
Comparator comparator = new SomeComparator();
Collections.sort(list, comparator);
For reference see the link: http://tutorials.jenkov.com/java-collections/sorting.html
If you have a problem in Android Studio and you have installed Android N, change the Android rendering version with an older one and the problem will disappear.
I use the following customization in Laravel to:
First, I'll create a file, helpers.php
, in the root of Laravel and insert the following:
<?php
if (!function_exists('database_driver')) {
function database_driver(): string
{
$connection = config('database.default');
return config('database.connections.' . $connection . '.driver');
}
}
if (!function_exists('is_database_driver')) {
function is_database_driver(string $driver): bool
{
return $driver === database_driver();
}
}
In composer.json, I'll insert the following into autoload
. This allows composer to auto-discover helpers.php.
"autoload": {
"files": [
"app/Services/Uploads/Processors/processor_functions.php",
"app/helpers.php"
]
},
I use the following in my Laravel models.
if (is_database_driver('sqlite')) {
$table->timestamps();
} else {
$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')
->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
}
This allows my team to continue using sqlite for unit tests. ON UPDATE CURRENT_TIMESTAMP
is a MySQL shortcut and is not available in sqlite.
If you want control over the duration and style of the animation, you can do:
[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
scrollView.contentOffset = CGPointMake(x, y);
} completion:NULL];
Adjust the duration (2.0f
) and options (UIViewAnimationOptionCurveLinear
) to taste!
You need to add overflow:auto
to your parent div for it to encompass the inner floated div:
<div style="margin:0 auto;width: 960px; min-height: 100px; background-color:orange;overflow:auto">
<div style="width:500px; height:200px; background-color:black; float:right">
</div>
</div>
You can have a regular Python module, say config.py, like this:
truck = dict(
color = 'blue',
brand = 'ford',
)
city = 'new york'
cabriolet = dict(
color = 'black',
engine = dict(
cylinders = 8,
placement = 'mid',
),
doors = 2,
)
and use it like this:
import config
print(config.truck['color'])
function Test(){
this.prop1 = 'prop1';
this.prop2 = 'prop2';
this.func1 = function(){
return this.prop1 + this.prop2;
}
};
Test.prototype.protoProp1 = 'protoProp1';
Test.prototype.protoProp2 = 'protoProp2';
var newKeywordTest = new Test();
var objectCreateTest = Object.create(Test.prototype);
/* Object.create */
console.log(objectCreateTest.prop1); // undefined
console.log(objectCreateTest.protoProp1); // protoProp1
console.log(objectCreateTest.__proto__.protoProp1); // protoProp1
/* new */
console.log(newKeywordTest.prop1); // prop1
console.log(newKeywordTest.__proto__.protoProp1); // protoProp1
Summary:
1) with new
keyword there are two things to note;
a) function is used as a constructor
b) function.prototype
object is passed to the __proto__
property ... or where __proto__
is not supported, it is the second place where the new object looks to find properties
2) with Object.create(obj.prototype)
you are constructing an object (obj.prototype
) and passing it to the intended object ..with the difference that now new object's __proto__
is also pointing to obj.prototype (please ref ans by xj9 for that)
private string[] GetLines(string text)
{
List<string> lines = new List<string>();
using (MemoryStream ms = new MemoryStream())
{
StreamWriter sw = new StreamWriter(ms);
sw.Write(text);
sw.Flush();
ms.Position = 0;
string line;
using (StreamReader sr = new StreamReader(ms))
{
while ((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
}
sw.Close();
}
return lines.ToArray();
}
My favorite no-conflict-friendly construct:
jQuery(function($) {
// ...
});
Calling jQuery with a function pointer is a shortcut for $(document).ready(...)
Or as we say in coffeescript:
jQuery ($) ->
# code here
Sometimes onsubmit
wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
This is what worked for me:
$.fn.datepicker.defaults.format = 'yy-mm-dd'
mvn install
will put your packaged maven project into the local repository, for local application using your project as a dependency.mvn release
will basically put your current code in a tag on your SCM, change your version in your projects.mvn deploy
will put your packaged maven project into a remote repository for sharing with other developers.Resources :
Make a std::pair
in function then sort pair :
generic version :
template< class RandomAccessIterator,class Compare >
auto sort2(RandomAccessIterator begin,RandomAccessIterator end,Compare cmp) ->
std::vector<std::pair<std::uint32_t,RandomAccessIterator>>
{
using valueType=typename std::iterator_traits<RandomAccessIterator>::value_type;
using Pair=std::pair<std::uint32_t,RandomAccessIterator>;
std::vector<Pair> index_pair;
index_pair.reserve(std::distance(begin,end));
for(uint32_t idx=0;begin!=end;++begin,++idx){
index_pair.push_back(Pair(idx,begin));
}
std::sort( index_pair.begin(),index_pair.end(),[&](const Pair& lhs,const Pair& rhs){
return cmp(*lhs.second,*rhs.second);
});
return index_pair;
}
Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.
The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.
The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.
The simplest solution, although a little time consuming would be to restart your computer or simple logout from the current user and login again.
The best way I found, aside of using a dedicated commit GUI, is to use git difftool -d
- This opens your diff tool in directory comparison mode, comparing HEAD with current dirty folder.
Try just --with-curl, without specifying a location, and see if it'll find it by itself.
class of my button is "input-addon btn btn-default fileinput-exists"
below code helped me
document.querySelector('.input-addon.btn.btn-default.fileinput-exists').click();
but I want to click second button, I have two buttons in my screen so I used querySelectorAll
var elem = document.querySelectorAll('.input-addon.btn.btn-default.fileinput-exists');
elem[1].click();
here elem[1] is the second button object that I want to click.