This might be obvious, but it has tripped me up with 404s a number of times... Make sure the fonts folder permissions are set correctly.
A clean way to download a file is:
import urllib
testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")
This downloads a file from a website and names it file.gz
. This is one of my favorite solutions, from Downloading a picture via urllib and python.
This example uses the urllib
library, and it will directly retrieve the file form a source.
Good question, although not a trivial one to answer.
Defines how transactions relate to each other. Common options:
REQUIRED
: Code will always run in a transaction. Creates a new transaction or reuses one if available.REQUIRES_NEW
: Code will always run in a new transaction. Suspends the current transaction if one exists.Defines the data contract between transactions.
ISOLATION_READ_UNCOMMITTED
: Allows dirty reads.ISOLATION_READ_COMMITTED
: Does not allow dirty reads.ISOLATION_REPEATABLE_READ
: If a row is read twice in the same transaction, the result will always be the same. ISOLATION_SERIALIZABLE
: Performs all transactions in a sequence.The different levels have different performance characteristics in a multi-threaded application. I think if you understand the dirty reads
concept you will be able to select a good option.
Example of when a dirty read can occur:
thread 1 thread 2
| |
write(x) |
| |
| read(x)
| |
rollback |
v v
value (x) is now dirty (incorrect)
So a sane default (if such can be claimed) could be ISOLATION_READ_COMMITTED
, which only lets you read values which have already been committed by other running transactions, in combination with a propagation level of REQUIRED
. Then you can work from there if your application has other needs.
A practical example of where a new transaction will always be created when entering the provideService
routine and completed when leaving:
public class FooService {
private Repository repo1;
private Repository repo2;
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void provideService() {
repo1.retrieveFoo();
repo2.retrieveFoo();
}
}
Had we instead used REQUIRED
, the transaction would remain open if the transaction was already open when entering the routine.
Note also that the result of a rollback
could be different as several executions could take part in the same transaction.
We can easily verify the behaviour with a test and see how results differ with propagation levels:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:/fooService.xml")
public class FooServiceTests {
private @Autowired TransactionManager transactionManager;
private @Autowired FooService fooService;
@Test
public void testProvideService() {
TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
fooService.provideService();
transactionManager.rollback(status);
// assert repository values are unchanged ...
}
With a propagation level of
REQUIRES_NEW
: we would expect fooService.provideService()
was NOT rolled back since it created it's own sub-transaction.
REQUIRED
: we would expect everything was rolled back and the backing store was unchanged.
setBackgroundResource(0)
is the best option. From the documentation:
Set the background to a given resource. The resource should refer to a Drawable object or 0 to remove the background.
It works everywhere, because it's since API 1.
setBackground
was added much later, in API 16, so it will not work if your minSdkVersion
is lower than 16.
Did you enable the session state in the section as well?
<system.web>
<pages enableSessionState="true" />
</system.web>
Or did you add this to the page?
<%@Page enableSessionState="true">
And did you verify that the ASP.NET Session State Manager Service
service is running? In your screenshot it isn't. It's set to start-up mode Manual
which requires you to start it every time you want to make use of it. To start it, highlight the service and click the green play button on the toolbar. To start it automatically, edit the properties and adjust the Start-up type.
Or set the SessionState's mode property to InProc
, so that the state service is not required.
<system.web>
<sessionState mode="InProc" />
</system.web>
Check MSDN for all the options available to you with regards to storing data in the ASP.NET session state.
Note: It's better to have your Controller fetch the value from the session and have it add the value to the Model for your page/control (or to the ViewBag), that way the View doesn't depend on the HttpSession and you can choose a different source for this item later with minimal code changes. Or even better, not use the session state at all. It can kill you performance when you're using a lot of async javascript calls.
@mayabelle you can create IHttpActionResult concrete and wrapped those code like this:
public class NotFoundPlainTextActionResult : IHttpActionResult
{
public NotFoundPlainTextActionResult(HttpRequestMessage request, string message)
{
Request = request;
Message = message;
}
public string Message { get; private set; }
public HttpRequestMessage Request { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(ExecuteResult());
}
public HttpResponseMessage ExecuteResult()
{
var response = new HttpResponseMessage();
if (!string.IsNullOrWhiteSpace(Message))
//response.Content = new StringContent(Message);
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception(Message));
response.RequestMessage = Request;
return response;
}
}
As other answers have stated, the ->
symbol is used as part of function annotations. In more recent versions of Python >= 3.5
, though, it has a defined meaning.
PEP 3107 -- Function Annotations described the specification, defining the grammar changes, the existence of func.__annotations__
in which they are stored and, the fact that it's use case is still open.
In Python 3.5
though, PEP 484 -- Type Hints attaches a single meaning to this: ->
is used to indicate the type that the function returns. It also seems like this will be enforced in future versions as described in What about existing uses of annotations:
The fastest conceivable scheme would introduce silent deprecation of non-type-hint annotations in 3.6, full deprecation in 3.7, and declare type hints as the only allowed use of annotations in Python 3.8.
(Emphasis mine)
This hasn't been actually implemented as of 3.6
as far as I can tell so it might get bumped to future versions.
According to this, the example you've supplied:
def f(x) -> 123:
return x
will be forbidden in the future (and in current versions will be confusing), it would need to be changed to:
def f(x) -> int:
return x
for it to effectively describe that function f
returns an object of type int
.
The annotations are not used in any way by Python itself, it pretty much populates and ignores them. It's up to 3rd party libraries to work with them.
The :target
-pseudo selector is made for these type of situations: http://reference.sitepoint.com/css/pseudoclass-target
It is supported by all modern browsers. To get some IE versions to understand it you can use something like Selectivizr
Here is a tab example with :target
-pseudo selector.
sudo apt-get update
For Mysql Database
sudo apt-get install php-mysql
For PostgreSQL Database
sudo apt-get install php-pgsql
Than
php artisan migrate
I'm running Qt 5.5 under Windows and the default constructor of QDir appears to pick up the current working directory, not the application directory.
I'm not sure if the getenv PWD will work cross-platform and I think it is set to the current working directory when the shell launched the application and doesn't include any working directory changes done by the app itself (which might be why the OP is seeing this behavior).
So I thought I'd add some other ways that should give you the current working directory (not the application's binary location):
// using where a relative filename will end up
QFileInfo fi("temp");
cout << fi.absolutePath() << endl;
// explicitly using the relative name of the current working directory
QDir dir(".");
cout << dir.absolutePath() << endl;
You can use window.location.reload();
in your componentDidMount()
lifecycle method. If you are using react-router
, it has a refresh method to do that.
Edit: If you want to do that after a data update, you might be looking to a re-render
not a reload
and you can do that by using this.setState(). Here is a basic example of it to fire a re-render
after data is fetched.
import React from 'react'
const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;
class MyComponent extends React.Component {
state = {
users: null
}
componentDidMount() {
fetch(url)
.then(response => response.json())
.then(users => this.setState({users: users}));
}
render() {
const {users} = this.state;
if (users) {
return (
<ul>
{users.map(user => <li>{user.name}</li>)}
</ul>
)
} else {
return (<h1>Loading ...</h1>)
}
}
}
export default MyComponent;
Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.
I have tried the following method and it even works with the extreme case like:
str1=' I live on earth '
' '.join(str1.split())
But if you prefer a regular expression it can be done as:
re.sub('\s+', ' ', str1)
Although some preprocessing has to be done in order to remove the trailing and ending space.
I agree with @Richard Morgan ... what you are doing should be working, so more information may be needed.
Microsoft has some suggestions on options to protect your Excel 2003 worksheets.
Here is a little more info ...
From help files (Protect Method):
expression.Protect(Password, Structure, Windows)
expression Required. An expression that returns a Workbook object.
Password Optional Variant. A string that specifies a case-sensitive password for the worksheet or workbook. If this argument is omitted, you can unprotect the worksheet or workbook without using a password. Otherwise, you must specify the password to unprotect the worksheet or workbook. If you forget the password, you cannot unprotect the worksheet or workbook. It's a good idea to keep a list of your passwords and their corresponding document names in a safe place.
Structure Optional Variant. True to protect the structure of the workbook (the relative position of the sheets). The default value is False.
Windows Optional Variant. True to protect the workbook windows. If this argument is omitted, the windows aren’t protected.
ActiveWorkbook.Protect Password:="password", Structure:=True, Windows:=True
If you want to work at the worksheet level, I used something similar years ago when I needed to protect/unprotect:
Sub ProtectSheet()
ActiveSheet.Protect "password", True, True
End Sub
Sub UnProtectSheet()
ActiveSheet.Unprotect "password"
End Sub
Sub protectAll()
Dim myCount
Dim i
myCount = Application.Sheets.Count
Sheets(1).Select
For i = 1 To myCount
ActiveSheet.Protect "password", true, true
If i = myCount Then
End
End If
ActiveSheet.Next.Select
Next i
End Sub
If you want to control the width of the list that drops down, you can do it as follows.
CSS
#wgtmsr option {
width: 50px;
}
Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length)
.
You can get this if the client specifies "https" but the server is only running "http". So, the server isn't expecting to make a secure connection.
I was getting an "out of space" error, which left me scratching my head as I had plenty of disk space, until I realized that it ran out of space on /tmp
, which on Arch Linux is mounted on a tmpfs
with a size limit.
use indexOf()
function
string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
//DO YOUR LOGIC
string errorCode = s.Substring(index+4);
}
I have to find distinct rows with the following details
class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries
public DbSet<SCountry> country { get; set; }
public List<SCountry> DoDistinct()
{
var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
return Countries;
}
There is a static constant that represents 0:
BigDecimal.ZERO.equals(selectPrice)
You should do this instead of:
selectPrice.equals(BigDecimal.ZERO)
in order to avoid the case where selectPrice
is null
.
getattr(x, 'y')
is equivalent to x.y
setattr(x, 'y', v)
is equivalent to x.y = v
delattr(x, 'y')
is equivalent to del x.y
Have you tried with a sub-query for every field:
UPDATE
MasterTbl
SET
TotalX = (SELECT SUM(X) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
TotalY = (SELECT SUM(Y) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID),
TotalZ = (SELECT SUM(Z) from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)
WHERE
....
In my case this turned out to be a bad USB hub.
The 'lsusb' command can be used to display all recognized devices. If the unit is not plugged in the option to set the speed will be disabled.
The lsusb command should output something like the string 'Future Technology Devices International, Ltd Bridge(I2C/SPI/UART/FIFO)' if your device is recognized. Mine was an RFDuino
My answer is based on the koma's but it doesn't require to override onStart but only onCreateView which is almost always overridden by default when you create new fragments.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_fragment_layout, container);
Rect displayRectangle = new Rect();
Window window = getDialog().getWindow();
window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
v.setMinimumWidth((int)(displayRectangle.width() * 0.9f));
v.setMinimumHeight((int)(displayRectangle.height() * 0.9f));
return v;
}
I've tested it on Android 5.0.1.
In Retrofit2, When you want to send your parameters in raw you must use Scalars.
first add this in your gradle:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
Your Interface
public interface ApiInterface {
String URL_BASE = "http://10.157.102.22/rest/";
@Headers("Content-Type: application/json")
@POST("login")
Call<User> getUser(@Body String body);
}
Activity
public class SampleActivity extends AppCompatActivity implements Callback<User> {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ApiInterface.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
// prepare call in Retrofit 2.0
try {
JSONObject paramObject = new JSONObject();
paramObject.put("email", "[email protected]");
paramObject.put("pass", "4384984938943");
Call<User> userCall = apiInterface.getUser(paramObject.toString());
userCall.enqueue(this);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onResponse(Call<User> call, Response<User> response) {
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
}
There is a way to mount a volume during a build, but it doesn't involve Dockerfiles.
The technique would be to create a container from whatever base you wanted to use (mounting your volume(s) in the container with the -v
option), run a shell script to do your image building work, then commit the container as an image when done.
Not only will this leave out the excess files you don't want (this is good for secure files as well, like SSH files), it also creates a single image. It has downsides: the commit command doesn't support all of the Dockerfile instructions, and it doesn't let you pick up when you left off if you need to edit your build script.
UPDATE:
For example,
CONTAINER_ID=$(docker run -dit ubuntu:16.04)
docker cp build.sh $CONTAINER_ID:/build.sh
docker exec -t $CONTAINER_ID /bin/sh -c '/bin/sh /build.sh'
docker commit $CONTAINER_ID $REPO:$TAG
docker stop $CONTAINER_ID
Don't sort the array to get the largest value.
Get the max value:
$value = max($array);
Get the corresponding key:
$key = array_search($value, $array);
You need to run
php artisan migrate:rollback
if that also fails just go in and drop all the tables which you may have to do as it seems your migration table is messed up or your user table when you ran a previous rollback did not drop the table.
EDIT:
The reason this happens is that you ran a rollback previously and it had some error in the code or did not drop the table. This still however messes up the laravel migration table and as far as it's concerned you now have no record of pushing the user table up. The user table does already exist however and this error is throw.
HTML:
<table id="uniquetable">
<thead>
<tr>
<th> {{ field[0].key }} </th>
<th> {{ field[1].key }} </th>
<th> {{ field[2].key }} </th>
<th> {{ field[3].key }} </th>
</tr>
</thead>
<tbody>
<tr v-for="obj in objects" v-bind:key="obj.id">
<td> {{ obj.id }} </td>
<td> {{ obj.name }} </td>
<td> {{ obj.age }} </td>
<td> {{ obj.gender }} </td>
</tr>
</tbody>
</table>
CSS:
#uniquetable thead{
display:block;
width: 100%;
}
#uniquetable tbody{
display:block;
width: 100%;
height: 100px;
overflow-y:overlay;
overflow-x:hidden;
}
#uniquetable tbody tr,#uniquetable thead tr{
width: 100%;
display:table;
}
#uniquetable tbody tr td, #uniquetable thead tr th{
display:table-cell;
width:20% !important;
overflow:hidden;
}
this will work as well:
#uniquetable tbody {
width:inherit !important;
display:block;
max-height: 400px;
overflow-y:overlay;
}
#uniquetable thead {
width:inherit !important;
display:block;
}
#uniquetable tbody tr, #uniquetable thead tr {
display:inline-flex;
width:100%;
}
#uniquetable tbody tr td, #uniquetable thead tr th {
display:block;
width:20%;
border-top:none;
text-overflow: ellipsis;
overflow: hidden;
max-height:400px;
}
If I understand your question correctly, this should help you:
TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1 .setFocusable(false);
child: Align(
alignment: Alignment.center,
child: Text(
'Text here',
textAlign: TextAlign.center,
),
),
This produced the best result for me.
$response
is instance of PSR-7 ResponseInterface
. For more details see https://www.php-fig.org/psr/psr-7/#3-interfaces
getBody()
returns StreamInterface
:
/**
* Gets the body of the message.
*
* @return StreamInterface Returns the body as a stream.
*/
public function getBody();
StreamInterface
implements __toString()
which does
Reads all data from the stream into a string, from the beginning to end.
Therefore, to read body as string, you have to cast it to string:
$stringBody = (string) $response->getBody()
json_decode($response->getBody()
is not the best solution as it magically casts stream into string for you. json_decode()
requires string as 1st argument.$response->getBody()->getContents()
unless you know what you're doing. If you read documentation for getContents()
, it says: Returns the remaining contents in a string
. Therefore, calling getContents()
reads the rest of the stream and calling it again returns nothing because stream is already at the end. You'd have to rewind the stream between those calls.We had an interesting issue come up at a company I previously worked at where we used friend to decent affect. I worked in our framework department we created a basic engine level system over our custom OS. Internally we had a class structure:
Game
/ \
TwoPlayer SinglePlayer
All of these classes were part of the framework and maintained by our team. The games produced by the company were built on top of this framework deriving from one of Games children. The issue was that Game had interfaces to various things that SinglePlayer and TwoPlayer needed access to but that we did not want expose outside of the framework classes. The solution was to make those interfaces private and allow TwoPlayer and SinglePlayer access to them via friendship.
Truthfully this whole issue could have been resolved by a better implementation of our system but we were locked into what we had.
It's quite simple, use
Long.valueOf(String s);
For example:
String s;
long l;
Scanner sc=new Scanner(System.in);
s=sc.next();
l=Long.valueOf(s);
System.out.print(l);
You're done!!!
Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.
One more that's not on his list:
[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816
But if all you want to do is subtract, why bother changing the input to base 10?
[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$
The dc
command is "desk calc". It will also take input from stdin, like bc
, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.
In the commands above we've got the following:
16i
-- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.BFCA3000
-- your initial number17FF
-- a random hex number I picked to subtract from your initial number-
-- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stackp
-- print the last item on the stack. This doesn't change the stack, so...10o
-- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".p
-- print the last item on the stack again ... this time in hex.You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.
I have 2 computers with VMWare Workstation and Mac OS Sierra installed as the guest OS. First machine could recognize my iOS device whereas my second machine could not recognize it. The second machine was exhibiting the same behavior as others reported where it would reconnect and disconnect with the iPhone endlessly.
Thankfully, my second machine had network connectivity problems with my VM. So I stumbled upon the solution when I reset my network settings for the VM.
You can try the following steps and see if it works for you. It worked for me.
Why not use a Single liner ...
IEnumerable<Book> _Book_IE= _Book_List as IEnumerable<Book>;
Pretty much all the answers currently add either leading spaces, trailing spaces or some other separator issue. To select from the fourth field where the separator is whitespace and the output separator is a single space using awk
would be:
awk '{for(i=4;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' file
To parametrize the starting field you could do:
awk '{for(i=n;i<=NF;i++)printf "%s",$i (i==NF?ORS:OFS)}' n=4 file
And also the ending field:
awk '{for(i=n;i<=m=(m>NF?NF:m);i++)printf "%s",$i (i==m?ORS:OFS)}' n=4 m=10 file
What is the utility of an only one Ampersand? This morning, I made a launcher in the XFCE panel (in Manjaro+XFCE) to launch 2 passwords managers simultaneously:
sh -c "keepassx && password-gorilla"
or
sh -c "keepassx; password-gorilla"
But it does not work as I want. I.E., the first app starts but the second starts only when the previous is closed
However, I found that (with only one ampersand):
sh -c "keepassx & password-gorilla"
and it works as I want now...
Java array reflection is for cases where you don't have an instance of the Class available to do "instanceof" on. For example, if you're writing some sort of injection framework, that injects values into a new instance of a class, such as JPA does, then you need to use the isArray() functionality.
I blogged about this earlier in December. http://blog.adamsbros.org/2010/12/08/java-array-reflection/
In case if you use new swift version.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ChannelMoreSegue" {
}
}
Maybe just use
window.parent
into your iframe to get the calling frame / windows. If you had multiple calling frame, you can use
window.top
V2 of Google reCAPTCHA.
Step 1 - Go to Google reCAPTCHA
Login then get Site Key and Secret Key
Step 2 - Download PHP code here and upload src folder on your server.
Step 3 - Use below code in your form.php
<head>
<title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
require('src/autoload.php');
$siteKey = '6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN';
$secret = '6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$gRecaptchaResponse = $_POST['g-recaptcha-response']; //google captcha post data
$remoteIp = $_SERVER['REMOTE_ADDR']; //to get user's ip
$recaptchaErrors = ''; // blank varible to store error
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha
if ($resp->isSuccess()) {
/********
Add code to create User here when form submission is successful
*****/
} else {
/****
// This variable will have error when reCAPTCHA is not entered correctly.
****/
$recaptchaErrors = $resp->getErrorCodes();
}
?>
<form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post">
<div class="panel periodic-login">
<div class="panel-body text-center">
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_user_name" required="">
<span class="bar"></span>
<label>Username</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_phone_number" required="">
<span class="bar"></span>
<label>Phone</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="password" autcomplete="off" class="form-text" name="new_user_password" required="">
<span class="bar"></span>
<label>Password</label>
</div>
<?php
if(isset($recaptchaErrors[0])){
print('Error in Submitting Form. Please Enter reCAPTCHA AGAIN');
}
?>
<div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div>
<input type="submit" class="btn col-md-12" value="Create User">
</div>
</div>
</form>
</body>
</html>
Try
python --version
or
python -V
This will return a current python version in terminal.
var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";_x000D_
var checkForSpecialChar = function(string){_x000D_
for(i = 0; i < specialChars.length;i++){_x000D_
if(string.indexOf(specialChars[i]) > -1){_x000D_
return true_x000D_
}_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
var str = "YourText";_x000D_
if(checkForSpecialChar(str)){_x000D_
alert("Not Valid");_x000D_
} else {_x000D_
alert("Valid");_x000D_
}
_x000D_
I know this has already been answered, but for anybody looking for a simple, no-frills implementation of a ViewPager indicator, I've implemented one that I've open sourced. For anyone finding Jake Wharton's version a bit complex for their needs, have a look at https://github.com/jarrodrobins/SimpleViewPagerIndicator.
You can use signals to control nginx.
According to documentation, you need to send HUP signal to nginx master process.
HUP - changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes
Check the documentation here: http://nginx.org/en/docs/control.html
You can send the HUP signal to nginx master process PID like this:
kill -HUP $( cat /var/run/nginx.pid )
The command above reads the nginx PID from /var/run/nginx.pid
. By default nginx pid is written to /usr/local/nginx/logs/nginx.pid
but that can be overridden in config. Check your nginx.config
to see where it saves the PID.
[UIView transitionWithView:textFieldimageView
duration:0.2f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
imageView.image = newImage;
} completion:nil];
is another possibility
I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)
There are two situations possible when we talk about passing data between activities.
Let's say there are two activities A and B and there is a String X. and you are in Activity A.
Now let's see the two cases
CASE 1:
String X is in A and you want to get it in Activity B.
It is very straightforward.
In Activity A.
1) Create Intent
2) Put Extra value
3) startActivity
Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)
In Activity B
Inside onCreate()
method retrieve string X using the key which you used while storing X (Your_KEY).
Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");
Case 2:
This case is little tricky if u are new to Android development Because you are in Activity A, you move to Activity B, collect the string, move back to Activity A and retrieve the collected String or data. Let's see how to deal with this situation.
In Activity A
1) Create Intent
2) start an activity with a request code.
Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);
In Activity B
1) Put string X in intent
2) Set result
3) Finish activity
Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent); // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();
Again in Activity A
1) Override onActivityResult method
onActivityResult(int req_code, int res_code, Intent data)
{
if(req_code==your_req_code)
{
String X = data.getStringExtra("KEY")
}
}
You might wonder what is the reqCode, resCode in the onActivityResult(int reqCode, resCode, Intent data)
reqCode is useful when you have to identify from which activity you are getting the result from.
Let's say you have two buttons, one button starts Camera (you click a photo and get the bitmap of that image in your Activity as a result), another button starts GoogleMap( you get back the current coordinates of your location as a result). So to distinguish between the results of both activities you start CameraActivty and MapActivity with different request codes.
resCode: is useful when you have to distinguish between how results are coming back to requesting activity.
For eg: You start Camera Activity. When the camera activity starts, you could either take a photo or just move back to requesting activity without taking a photo with the back button press. So in these two situations, your camera activity sends result with different resCode ACTIVITY.RESULT_OK and ACTIVITY.RESULT_CANCEL respectively.
Relevant Links
I figured out a way using https://github.com/springfox/springfox and https://github.com/RobWin/swagger2markup
Used Swagger 2 to implement documentation.
Let me add a little detail to this.
these two calls are almost equivalent:
func.call(context, ...args); // pass an array as list with spread operator
func.apply(context, args); // is same as using apply
There’s only a minor difference:
- The
spread
operator ... allows passing iterableargs
as the list to call.- The
apply
accepts only array-like args.
So, these calls complement each other. Where we expect an iterable, call
works, where we expect an array-like, apply
works.
And for objects that are both iterable and array-like, like a real array, we technically could use any of them, but apply will probably be faster because most JavaScript engines internally optimize it better.
If you want to view the versions of files a tag is pointing to, you can do a git checkout, though this puts your repository in “detached HEAD” state, which has some ill side effects:
$ git checkout 2.0.0
Note: checking out '2.0.0'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:
git checkout -b <new-branch-name>
HEAD is now at 99ada87... Merge pull request #89 from schacon/appendix-final
$ git checkout 2.0-beta-0.1
Previous HEAD position was 99ada87... Merge pull request #89 from schacon/appendix-final
HEAD is now at df3f601... add atlas.json and cover image
In “detached HEAD” state, if you make changes and then create a commit, the tag will stay the same, but your new commit won’t belong to any branch and will be unreachable, except for by the exact commit hash. Thus, if you need to make changes—say you’re fixing a bug on an older version, for instance—you will generally want to create a branch:
$ git checkout -b version2 v2.0.0
Switched to a new branch 'version2'
If you do this and make a commit, your version2 branch will be slightly different than your v2.0.0 tag since it will move forward with your new changes, so do be careful.
You can have only one default export which you declare like:
export default App;
or
export default class App extends React.Component {...
and later do import App from './App'
If you want to export something more you can use named exports which you declare without default
keyword like:
export {
About,
Contact,
}
or:
export About;
export Contact;
or:
export const About = class About extends React.Component {....
export const Contact = () => (<div> ... </div>);
and later you import them like:
import App, { About, Contact } from './App';
EDIT:
There is a mistake in the tutorial as it is not possible to make 3 default exports in the same main.js
file. Other than that why export anything if it is no used outside the file?. Correct main.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'
class App extends React.Component {
...
}
class Home extends React.Component {
...
}
class About extends React.Component {
...
}
class Contact extends React.Component {
...
}
ReactDOM.render((
<Router history = {browserHistory}>
<Route path = "/" component = {App}>
<IndexRoute component = {Home} />
<Route path = "home" component = {Home} />
<Route path = "about" component = {About} />
<Route path = "contact" component = {Contact} />
</Route>
</Router>
), document.getElementById('app'))
EDIT2:
another thing is that this tutorial is based on react-router-V3 which has different api than v4.
Ok, personal opinion here, but Append and Prepend imply precise positions in a set.
Push and Pop are really concepts that can be applied to either end of a set... Just as long as you're consistent... For some reason, to me, Push() seems like it should apply to the front of a set...
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
Use the response contained within the exception. Here is an example:
import boto3
from botocore.exceptions import ClientError
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print("Created user: %s" % user)
except ClientError as e:
if e.response['Error']['Code'] == 'EntityAlreadyExists':
print("User already exists")
else:
print("Unexpected error: %s" % e)
The response dict in the exception will contain the following:
['Error']['Code']
e.g. 'EntityAlreadyExists' or 'ValidationError'['ResponseMetadata']['HTTPStatusCode']
e.g. 400['ResponseMetadata']['RequestId']
e.g. 'd2b06652-88d7-11e5-99d0-812348583a35'['Error']['Message']
e.g. "An error occurred (EntityAlreadyExists) ..."['Error']['Type']
e.g. 'Sender'For more information see:
[Updated: 2018-03-07]
The AWS Python SDK has begun to expose service exceptions on clients (though not on resources) that you can explicitly catch, so it is now possible to write that code like this:
import botocore
import boto3
try:
iam = boto3.client('iam')
user = iam.create_user(UserName='fred')
print("Created user: %s" % user)
except iam.exceptions.EntityAlreadyExistsException:
print("User already exists")
except botocore.exceptions.ParamValidationError as e:
print("Parameter validation error: %s" % e)
except botocore.exceptions.ClientError as e:
print("Unexpected error: %s" % e)
Unfortunately, there is currently no documentation for these exceptions but you can get a list of them as follows:
import botocore
import boto3
dir(botocore.exceptions)
Note that you must import both botocore and boto3. If you only import botocore then you will find that botocore has no attribute named exceptions
. This is because the exceptions are dynamically populated into botocore by boto3.
May be Everything? It supports regexps and has a console util too.
I noticed following line from error.
exact fetch returns more than requested number of rows
That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.
Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.
So, I truncated dual
table and inserted only row which X
value. And, everything working fine.
Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.
Try find / -iname '*numpy*'
More elegant option:
String phone = "+34666777888";
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null));
startActivity(intent);
I found these lines in one of the .sql files
"To connect with a manager that does not use port 3306
, you must specify the port number:
$mysqli = new mysqli('127.0.0.0.1','user','password','database','3307');
or, in procedural terms:
$mysqli = mysqli_connect('127.0.0.0.1','user','password','database','3307');"
It resolved the error for me . So i will suggest must use port number while making connection to server to resolve the error 1049
(unknown database).
Since an array has a fixed size that is allocated when created, your only option is to create a new array without the element you want to remove.
If the element you want to remove is the last array item, this becomes easy to implement using Arrays.copy
:
int a[] = { 1, 2, 3};
a = Arrays.copyOf(a, 2);
After running the above code, a will now point to a new array containing only 1, 2.
Otherwise if the element you want to delete is not the last one, you need to create a new array at size-1 and copy all the items to it except the one you want to delete.
The approach above is not efficient. If you need to manage a mutable list of items in memory, better use a List. Specifically LinkedList
will remove an item from the list in O(1)
(fastest theoretically possible).
Update:
I use Compare plugin 2 for notepad++ 7.5 and newer versions. Notepad++ 7.5 and newer versions does not have plugin manager. You have to download and install plugins manually. And YES it matters if you use 64bit or 32bit (86x).
So Keep in mind, if you use 64 bit version of Notepad++, you should also use 64 bit version of plugin, and the same valid for 32bit.
I wrote a guideline how to install it:
Note:
It is also possible to drag and drop the plugin.dll
file directly in plugin folder.
64bit:%programfiles%\Notepad++\plugins
32bit:%programfiles(x86)%\Notepad++\plugins
Update Thanks to @TylerH with this update: Notepad++ Now has "Plugin Admin" as a replacement for the old Plugin Manager. But this method (answer) is still valid for adding plugins manually for almost any Notepad++ plugins.
Disclaimer: the link of this guideline refer to my personal web site.
(Posted on behalf of the OP).
I believe I figured it out.
In my case, I added [class*="col-"] {padding: 0 7.5px;};
.
Then added .row {margin: 0 -7.5px;}
.
This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;}
to .row {margin: 0 -8.5px;}
, then it works perfectly.
I have no idea why there is a 1px margin. Maybe someone can explain it?
See the sample I created:
In addition to the most upvoted answer, it might be good to remove these as well for the sake of cleanness.
better to use touchstart
event with .on()
jQuery method:
$(window).load(function() { // better to use $(document).ready(function(){
$('.List li').on('click touchstart', function() {
$('.Div').slideDown('500');
});
});
And i don't understand why you are using $(window).load()
method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready()
method which does not wait for each element on the page to be loaded first.
I wrote a package (https://github.com/alexsanjoseph/compareDF) since I had the same issue.
> df1 <- data.frame(a = 1:5, b=letters[1:5], row = 1:5)
> df2 <- data.frame(a = 1:3, b=letters[1:3], row = 1:3)
> df_compare = compare_df(df1, df2, "row")
> df_compare$comparison_df
row chng_type a b
1 4 + 4 d
2 5 + 5 e
A more complicated example:
library(compareDF)
df1 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
"Hornet 4 Drive", "Duster 360", "Merc 240D"),
id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Mer"),
hp = c(110, 110, 181, 110, 245, 62),
cyl = c(6, 6, 4, 6, 8, 4),
qsec = c(16.46, 17.02, 33.00, 19.44, 15.84, 20.00))
df2 = data.frame(id1 = c("Mazda RX4", "Mazda RX4 Wag", "Datsun 710",
"Hornet 4 Drive", " Hornet Sportabout", "Valiant"),
id2 = c("Maz", "Maz", "Dat", "Hor", "Dus", "Val"),
hp = c(110, 110, 93, 110, 175, 105),
cyl = c(6, 6, 4, 6, 8, 6),
qsec = c(16.46, 17.02, 18.61, 19.44, 17.02, 20.22))
> df_compare$comparison_df
grp chng_type id1 id2 hp cyl qsec
1 1 - Hornet Sportabout Dus 175 8 17.02
2 2 + Datsun 710 Dat 181 4 33.00
3 2 - Datsun 710 Dat 93 4 18.61
4 3 + Duster 360 Dus 245 8 15.84
5 7 + Merc 240D Mer 62 4 20.00
6 8 - Valiant Val 105 6 20.22
The package also has an html_output command for quick checking
You can only use one color but as many images as you want, here is the format:
background: [ <bg-layer> , ]* <final-bg-layer>
<bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2}
<final-bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <background-color>
or
background: url(image1.png) center bottom no-repeat, url(image2.png) left top no-repeat;
If you need more colors, make an image of a solid color and use it. I know it’s not what you want to hear, but I hope it helps.
The format is from http://www.css3.info/preview/multiple-backgrounds/
If you are using .net core, then during development you can bypass certificate validation by using compiler directives. This way will only validate certificate for release and not for debug:
#if (DEBUG)
client.ClientCredentials.ServiceCertificate.SslCertificateAuthentication =
new X509ServiceCertificateAuthentication()
{
CertificateValidationMode = X509CertificateValidationMode.None,
RevocationMode = System.Security.Cryptography.X509Certificates.X509RevocationMode.NoCheck
}; #endif
One of the things that you might want to try out is starting eclipse with the -clean
option. If you have chosen to have eclipse use the same workspace every time then there is nothing else you need to do after that. With that option in place the workspace should be cleaned out.
However, if you don't have a default workspace chosen, when opening up eclipse you will be prompted to choose the workspace. At this point, choose the workspace you want cleaned up.
See "How to run eclipse in clean mode" and "Keeping Eclipse running clean" for more details.
I did this, also with jQuery:
$('input[type=search]').on('focus', function(){
// replace CSS font-size with 16px to disable auto zoom on iOS
$(this).data('fontSize', $(this).css('font-size')).css('font-size', '16px');
}).on('blur', function(){
// put back the CSS font-size
$(this).css('font-size', $(this).data('fontSize'));
});
Of course, some other elements in the interface may have to be adapted if this 16px
font-size breaks the design.
Just a single line to be added...
Add android:windowSoftInputMode="stateHidden|adjustPan"
in required activity of your manifest file
.
I just got solved :) :)
Add some more RAM and use SSD drive. Android Studio is best run on 8 to 12 GB of RAM using SSD drives based on my experience.
The file hello.py is not an executable file. You need to specify a file like python.exe
try following:
import sys
subprocess.call([sys.executable, 'hello.py', 'htmlfilename.htm'])
UrlCreateFromPath to the rescue! Well, not entirely, as it doesn't support extended and UNC path formats, but that's not so hard to overcome:
public static Uri FileUrlFromPath(string path)
{
const string prefix = @"\\";
const string extended = @"\\?\";
const string extendedUnc = @"\\?\UNC\";
const string device = @"\\.\";
const StringComparison comp = StringComparison.Ordinal;
if(path.StartsWith(extendedUnc, comp))
{
path = prefix+path.Substring(extendedUnc.Length);
}else if(path.StartsWith(extended, comp))
{
path = prefix+path.Substring(extended.Length);
}else if(path.StartsWith(device, comp))
{
path = prefix+path.Substring(device.Length);
}
int len = 1;
var buffer = new StringBuilder(len);
int result = UrlCreateFromPath(path, buffer, ref len, 0);
if(len == 1) Marshal.ThrowExceptionForHR(result);
buffer.EnsureCapacity(len);
result = UrlCreateFromPath(path, buffer, ref len, 0);
if(result == 1) throw new ArgumentException("Argument is not a valid path.", "path");
Marshal.ThrowExceptionForHR(result);
return new Uri(buffer.ToString());
}
[DllImport("shlwapi.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern int UrlCreateFromPath(string path, StringBuilder url, ref int urlLength, int reserved);
In case the path starts with with a special prefix, it gets removed. Although the documentation doesn't mention it, the function outputs the length of the URL even if the buffer is smaller, so I first obtain the length and then allocate the buffer.
Some very interesting observation I had is that while "\\device\path" is correctly transformed to "file://device/path", specifically "\\localhost\path" is transformed to just "file:///path".
The WinApi function managed to encode special characters, but leaves Unicode-specific characters unencoded, unlike the Uri construtor. In that case, AbsoluteUri contains the properly encoded URL, while OriginalString can be used to retain the Unicode characters.
Along with Java 14, it starts supporting Record. You may want to check that https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Record.html
public record Person (String name, String address) {}
Person person = new Person("Esteban", "Stormhaven, Tamriel");
And there are Sealed Classes after Java 15. https://openjdk.java.net/jeps/360
sealed interface Shape permits Circle, Rectangle {
record Circle(Point center, int radius) implements Shape { }
record Rectangle(Point lowerLeft, Point upperRight) implements Shape { }
}
For Back Button in jquery // http://code.jquery.com/jquery-latest.js
jQuery(window).bind("unload", function() { //
and in html5 there is an event The event is called 'popstate'
window.onpopstate = function(event) {
alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
and for refresh please check Check if page gets reloaded or refreshed in Javascript
In Mozilla Client-x and client-y is inside document area https://developer.mozilla.org/en-US/docs/Web/API/event.clientX
Save the following program as print.py
:
#!/usr/bin/python3
print('Hello World')
Then in the terminal type:
chmod +x print.py
./print.py
@jasper's answer is totally correct but with modern browsers, a standard Javascript solution could be:
function isScriptLoaded(src)
{
return document.querySelector('script[src="' + src + '"]') ? true : false;
}
for object "pega" that provides StartRunning(), StopRunning(), boolean getIsRunning() and integer getProgress100() returning value in range of 0 to 100, this provides text progress bar while running...
now = time.time()
timeout = now + 30.0
last_progress = -1
pega.StartRunning()
while now < timeout and pega.getIsRunning():
time.sleep(0.5)
now = time.time()
progress = pega.getTubProgress100()
if progress != last_progress:
print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", end='', flush=True)
last_progress = progress
pega.StopRunning()
progress = pega.getTubProgress100()
print('\r'+'='*progress+'-'*(100-progress)+' ' + str(progress) + "% ", flush=True)
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
Sample function is used for sample data in ORACLE. So you can try like this:-
SELECT * FROM TABLE_NAME SAMPLE(50);
Here 50 is the percentage of data contained by the table. So if you want 1000 rows from 100000. You can execute a query like:
SELECT * FROM TABLE_NAME SAMPLE(1);
Hope this can help you.
50 Meg is the max for Cell data download.
But you might be able to keep it under that in the app store and then have the app download other content after the user install and runs the app, so the app can be bigger. But not sure what the apple rules are for this.
I know that all in-app purchases need to be approved, but not sure if this kind of content needs to be approved.
In NuGet 3.0 the Get-Package
command is deprecated and replaced with Find-Package
command.
Find-Package Common.Logging -AllVersions
See the NuGet command reference docs for details.
This is the message shown if you try to use Get-Package in Visual Studio 2015.
This Command/Parameter combination has been deprecated and will be removed
in the next release. Please consider using the new command that replaces it:
'Find-Package [-Id] -AllVersions'
Or as @Yishai said, you can use the version number dropdown in the NuGet screen in Visual Studio.
If you want it outside of loop then use the below code.
<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id );
echo $display_name;
?>
Try this
function checkForm($fields){
foreach($fields as $field){
if($field['required'] && strlen($_POST[$field['name']]) <= 0){
$field['value'] = "Some error";
}
}
return $field;
}
To get value, use:
$.each($('input'),function(i,val){
if($(this).attr("type")=="hidden"){
var valueOfHidFiled=$(this).val();
alert(valueOfHidFiled);
}
});
or:
var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);
To set value, use:
$('input[type=hidden]').attr('value',newValue);
The default parser can parse your input. So you don't need a custom formatter and
String dateTime = "2012-02-22T02:06:58.147Z";
ZonedDateTime d = ZonedDateTime.parse(dateTime);
works as expected.
Maybe it's funny, but this works for me:
string.Join("",List1) != string.Join("", List2)
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
You can modify the id
without having to use getElementById
Example:
<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>
You can see it here: http://jsbin.com/elikaj/1/
Tested with Mozilla Firefox 22 and Google Chrome 60.0
Instruction from AWS EC2 support:
this will save the updated authorized_keys file
now try open a new SSH session to your instance using your new key pai
When you've confirmed you're able to SSH into the instance using the new key pair, u can vi .ssh/authorized_key and delete the old key.
Answer to Shaggie remark:
If you are unable to connect to the instance (e.g. key is corrupted) than use the AWS console to detach the volume (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html) and reattach it to working instance, than change the key on the volume and reattach it back to the previous instance.
In SQL Server 2012 and higher, this will format a number with commas:
select format([Number], 'N0')
You can also change 0
to the number of decimal places you want.
Using this script you can show all the databases name and files used (with exception of system dbs).
select name,physical_name from sys.master_files where database_id > 4
Once you get your environment up and running, this is helpful in giving you a basic app that users can log into.
Restful Authentication with all the bells and whistles: http://railsforum.com/viewtopic.php?id=14216&p=1
In your GET action, create an object of your view model, load the EmployeeList
collection property and send that to the view.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.EmployeesList = new List<Employee>
{
new Employee { Id = 1, FullName = "Shyju" },
new Employee { Id = 2, FullName = "Bryan" }
};
return View(vm);
}
And in your create view, create a new SelectList
object from the EmployeeList
property and pass that as value for the asp-items
property.
@model MyViewModel
<form asp-controller="Home" asp-action="Create">
<select asp-for="EmployeeId"
asp-items="@(new SelectList(Model.EmployeesList,"Id","FullName"))">
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
And your HttpPost action method to accept the submitted form data.
[HttpPost]
public IActionResult Create(MyViewModel model)
{
// check model.EmployeeId
// to do : Save and redirect
}
Or
If your view model has a List<SelectListItem>
as the property for your dropdown items.
public class MyViewModel
{
public int EmployeeId { get; set; }
public string Comments { get; set; }
public List<SelectListItem> Employees { set; get; }
}
And in your get action,
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Sean", Value = "2"}
};
return View(vm);
}
And in the view, you can directly use the Employees
property for the asp-items
.
@model MyViewModel
<form asp-controller="Home" asp-action="Create">
<label>Comments</label>
<input type="text" asp-for="Comments"/>
<label>Lucky Employee</label>
<select asp-for="EmployeeId" asp-items="@Model.Employees" >
<option>Please select one</option>
</select>
<input type="submit"/>
</form>
The class SelectListItem
belongs to Microsoft.AspNet.Mvc.Rendering
namespace.
Make sure you are using an explicit closing tag for the select element. If you use the self closing tag approach, the tag helper will render an empty SELECT element!
The below approach will not work
<select asp-for="EmployeeId" asp-items="@Model.Employees" />
But this will work.
<select asp-for="EmployeeId" asp-items="@Model.Employees"></select>
The above examples are using hard coded items for the options. So i thought i will add some sample code to get data using Entity framework as a lot of people use that.
Let's assume your DbContext object has a property called Employees
, which is of type DbSet<Employee>
where the Employee
entity class has an Id
and Name
property like this
public class Employee
{
public int Id { set; get; }
public string Name { set; get; }
}
You can use a LINQ query to get the employees and use the Select method in your LINQ expression to create a list of SelectListItem
objects for each employee.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = context.Employees
.Select(a => new SelectListItem() {
Value = a.Id.ToString(),
Text = a.Name
})
.ToList();
return View(vm);
}
Assuming context
is your db context object. The view code is same as above.
Some people prefer to use SelectList
class to hold the items needed to render the options.
public class MyViewModel
{
public int EmployeeId { get; set; }
public SelectList Employees { set; get; }
}
Now in your GET action, you can use the SelectList
constructor to populate the Employees
property of the view model. Make sure you are specifying the dataValueField
and dataTextField
parameters.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new SelectList(GetEmployees(),"Id","FirstName");
return View(vm);
}
public IEnumerable<Employee> GetEmployees()
{
// hard coded list for demo.
// You may replace with real data from database to create Employee objects
return new List<Employee>
{
new Employee { Id = 1, FirstName = "Shyju" },
new Employee { Id = 2, FirstName = "Bryan" }
};
}
Here I am calling the GetEmployees
method to get a list of Employee objects, each with an Id
and FirstName
property and I use those properties as DataValueField
and DataTextField
of the SelectList
object we created. You can change the hardcoded list to a code which reads data from a database table.
The view code will be same.
<select asp-for="EmployeeId" asp-items="@Model.Employees" >
<option>Please select one</option>
</select>
Sometimes you might want to render a select element from a list of strings. In that case, you can use the SelectList
constructor which only takes IEnumerable<T>
var vm = new MyViewModel();
var items = new List<string> {"Monday", "Tuesday", "Wednesday"};
vm.Employees = new SelectList(items);
return View(vm);
The view code will be same.
Some times,you might want to set one option as the default option in the SELECT element (For example, in an edit screen, you want to load the previously saved option value). To do that, you may simply set the EmployeeId
property value to the value of the option you want to be selected.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "11"},
new SelectListItem {Text = "Tom", Value = "12"},
new SelectListItem {Text = "Jerry", Value = "13"}
};
vm.EmployeeId = 12; // Here you set the value
return View(vm);
}
This will select the option Tom in the select element when the page is rendered.
If you want to render a multi select dropdown, you can simply change your view model property which you use for asp-for
attribute in your view to an array type.
public class MyViewModel
{
public int[] EmployeeIds { get; set; }
public List<SelectListItem> Employees { set; get; }
}
This will render the HTML markup for the select element with the multiple
attribute which will allow the user to select multiple options.
@model MyViewModel
<select id="EmployeeIds" multiple="multiple" name="EmployeeIds">
<option>Please select one</option>
<option value="1">Shyju</option>
<option value="2">Sean</option>
</select>
Similar to single select, set the EmployeeIds
property value to the an array of values you want.
public IActionResult Create()
{
var vm = new MyViewModel();
vm.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "11"},
new SelectListItem {Text = "Tom", Value = "12"},
new SelectListItem {Text = "Jerry", Value = "13"}
};
vm.EmployeeIds= new int[] { 12,13} ;
return View(vm);
}
This will select the option Tom and Jerry in the multi select element when the page is rendered.
If you do not prefer to keep a collection type property to pass the list of options to the view, you can use the dynamic ViewBag to do so.(This is not my personally recommended approach as viewbag is dynamic and your code is prone to uncatched typo errors)
public IActionResult Create()
{
ViewBag.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Sean", Value = "2"}
};
return View(new MyViewModel());
}
and in the view
<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
<option>Please select one</option>
</select>
It is same as above. All you have to do is, set the property (for which you are binding the dropdown for) value to the value of the option you want to be selected.
public IActionResult Create()
{
ViewBag.Employees = new List<SelectListItem>
{
new SelectListItem {Text = "Shyju", Value = "1"},
new SelectListItem {Text = "Bryan", Value = "2"},
new SelectListItem {Text = "Sean", Value = "3"}
};
vm.EmployeeId = 2; // This will set Bryan as selected
return View(new MyViewModel());
}
and in the view
<select asp-for="EmployeeId" asp-items="@ViewBag.Employees">
<option>Please select one</option>
</select>
The select tag helper method supports grouping options in a dropdown. All you have to do is, specify the Group
property value of each SelectListItem
in your action method.
public IActionResult Create()
{
var vm = new MyViewModel();
var group1 = new SelectListGroup { Name = "Dev Team" };
var group2 = new SelectListGroup { Name = "QA Team" };
var employeeList = new List<SelectListItem>()
{
new SelectListItem() { Value = "1", Text = "Shyju", Group = group1 },
new SelectListItem() { Value = "2", Text = "Bryan", Group = group1 },
new SelectListItem() { Value = "3", Text = "Kevin", Group = group2 },
new SelectListItem() { Value = "4", Text = "Alex", Group = group2 }
};
vm.Employees = employeeList;
return View(vm);
}
There is no change in the view code. the select tag helper will now render the options inside 2 optgroup items.
Add keyword static
to class declaration:
// this is a non-generic static class
public static class LinqHelper
{
}
I can't see why you would care. Other than the "don't use ports below 1024" privilege rule, you should be able to use any port because your clients should be configurable to talk to any IP address and port!
If they're not, then they haven't been done very well. Go back and do them properly :-)
In other words, run the server at IP address X
and port Y
then configure clients with that information. Then, if you find you must run a different server on X
that conflicts with your Y
, just re-configure your server and clients to use a new port. This is true whether your clients are code, or people typing URLs into a browser.
I, like you, wouldn't try to get numbers assigned by IANA since that's supposed to be for services so common that many, many environments will use them (think SSH or FTP or TELNET).
Your network is your network and, if you want your servers on port 1234 (or even the TELNET or FTP ports for that matter), that's your business. Case in point, in our mainframe development area, port 23 is used for the 3270 terminal server which is a vastly different beast to telnet. If you want to telnet to the UNIX side of the mainframe, you use port 1023. That's sometimes annoying if you use telnet clients without specifying port 1023 since it hooks you up to a server that knows nothing of the telnet protocol - we have to break out of the telnet client and do it properly:
telnet big_honking_mainframe_box.com 1023
If you really can't make the client side configurable, pick one in the second range, like 48042, and just use it, declaring that any other software on those boxes (including any added in the future) has to keep out of your way.
Following is an example. You can see the details http://jkssweetlife.com/configure-slf4j-working-various-logging-frameworks/ and download the full codes here.
Add following dependency to your pom if you are using maven, otherwise, just download the jar files and put on your classpath
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
Configure log4j.properties
log4j.rootLogger=TRACE, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss.SSS} %-5p [%c] - %m%n
Java example
public class Slf4jExample {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(Slf4jExample.class);
final String message = "Hello logging!";
logger.trace(message);
logger.debug(message);
logger.info(message);
logger.warn(message);
logger.error(message);
}
}
The easiest way is to make the "button image" as a separate image. Then place it over the main image (using "style="position: absolute;". Assign the URL link to "button image". and smile :)
Just add -o nonempty
in command line, like this:
s3fs -o nonempty <bucket-name> </mount/point/>
The question asks: "How can it be done in Python 3?"
Use this construct with Python 3.x:
for item in [1,2,3,4]:
print(item, " ", end="")
This will generate:
1 2 3 4
See this Python doc for more information:
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
--
Aside:
in addition, the print()
function also offers the sep
parameter that lets one specify how individual items to be printed should be separated. E.g.,
In [21]: print('this','is', 'a', 'test') # default single space between items
this is a test
In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest
In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test
Just adding for who might need.. Don't forget to alter the table!
ALTER TABLE table_name ADD FULLTEXT(column_name);
Since you declare sample
inside the anonymous function you pass to ready
, it is scoped to that function.
You then pass a string to setTimeout
which is eval
ed after 2 seconds. This takes place outside the current scope, so it can't find the function.
Only pass functions to setTimeout
, using eval is inefficient and hard to debug.
setTimeout(sample,2000)
If you wish to create a pdf from php, pdflib will help you (as some others suggested).
Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.
So, the options I know are:
DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.
HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.
Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:
wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.
htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.
I wouldn't advise you to do this but on my personal computer I disabled the firewall so that maven could get the required plugins.
Window -> Show View -> Other -> Studio/Remote
(Drag this tabbed window wherever)
Click the add FTP button (see below); #profit
Have you tried performing an svn cleanup?
This should do it:
<style>
body {
background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>
It is a generic type constraint. In this case it means that the generic type T
has to be a reference type (class, interface, delegate, or array type).
ResultSet
to your main program or do your stuff in the same method.Two suggestions:
std::deque
instead of std::vector
for better performance in your specific case and use the method std::deque::pop_front()
.&
in std::vector<ScanRule>& topPriorityRules;
This is really simple... I really get irritated when I found the solution. There was just one more back slash missing. This is it:
sed -i "s/\\\\\n//g" filename
If you add a $scope.$apply();
right after $scope.pluginsDisplayed.splice(index,1);
then it works.
I am not sure why this is happening, but basically when AngularJS doesn't know that the $scope has changed, it requires to call $apply manually. I am also new to AngularJS so cannot explain this better. I need too look more into it.
I found this awesome article that explains it quite properly. Note: I think it might be better to use ng-click (docs) rather than binding to "mousedown". I wrote a simple app here (http://avinash.me/losh, source http://github.com/hardfire/losh) based on AngularJS. It is not very clean, but it might be of help.
It's as simple as that:
function isMacintosh() {
return navigator.platform.indexOf('Mac') > -1
}
function isWindows() {
return navigator.platform.indexOf('Win') > -1
}
You can do funny things then like:
var isMac = isMacintosh();
var isPC = !isMacintosh();
Use the TRY_CONVERT function.
Create a user defined function. This will avoid the issues that Fedor Hajdu mentioned with regards to currency, fractional numbers, etc:
CREATE FUNCTION dbo.TryConvertInt(@Value varchar(18))
RETURNS int
AS
BEGIN
SET @Value = REPLACE(@Value, ',', '')
IF ISNUMERIC(@Value + 'e0') = 0 RETURN NULL
IF ( CHARINDEX('.', @Value) > 0 AND CONVERT(bigint, PARSENAME(@Value, 1)) <> 0 ) RETURN NULL
DECLARE @I bigint =
CASE
WHEN CHARINDEX('.', @Value) > 0 THEN CONVERT(bigint, PARSENAME(@Value, 2))
ELSE CONVERT(bigint, @Value)
END
IF ABS(@I) > 2147483647 RETURN NULL
RETURN @I
END
GO
-- Testing
DECLARE @Test TABLE(Value nvarchar(50)) -- Result
INSERT INTO @Test SELECT '1234' -- 1234
INSERT INTO @Test SELECT '1,234' -- 1234
INSERT INTO @Test SELECT '1234.0' -- 1234
INSERT INTO @Test SELECT '-1234' -- -1234
INSERT INTO @Test SELECT '$1234' -- NULL
INSERT INTO @Test SELECT '1234e10' -- NULL
INSERT INTO @Test SELECT '1234 5678' -- NULL
INSERT INTO @Test SELECT '123-456' -- NULL
INSERT INTO @Test SELECT '1234.5' -- NULL
INSERT INTO @Test SELECT '123456789000000' -- NULL
INSERT INTO @Test SELECT 'N/A' -- NULL
SELECT Value, dbo.TryConvertInt(Value) FROM @Test
Reference: I used this page extensively when creating my solution.
There doesn't seem to be a standard way to embed a version string in a python package. Most packages I've seen use some variant of your solution, i.e. eitner
Embed the version in setup.py
and have setup.py
generate a module (e.g. version.py
) containing only version info, that's imported by your package, or
The reverse: put the version info in your package itself, and import that to set the version in setup.py
Using ES6 the javascript becomes a little cleaner
handleFiles(input) {
const file = input.target.files[0];
const reader = new FileReader();
reader.onload = (event) => {
const file = event.target.result;
const allLines = file.split(/\r\n|\n/);
// Reading line by line
allLines.forEach((line) => {
console.log(line);
});
};
reader.onerror = (event) => {
alert(event.target.error.name);
};
reader.readAsText(file);
}
For those who want to implement a hack for Safari 7.0 and below, but not 7.1 and above -- use:
.myclass { (;property: value;); }
.myclass { [;property: value;]; }
On Windows Server 2012 with IIS 8 I have solved this by enabling ASP.NET 4.5 feature:
and then following ken's answer.
The way I use a yes/no prompt is:
If MsgBox("Are you sure?", MsgBoxStyle.YesNo) <> MsgBoxResults.Yes Then
Exit Sub
End If
See http://www.w3schools.com/tags/att_input_accept.asp:
The accept attribute is supported in all major browsers, except Internet Explorer and Safari. Definition and Usage
The accept attribute specifies the types of files that the server accepts (that can be submitted through a file upload).
Note: The accept attribute can only be used with
<input type="file">
.Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.
Syntax
<input accept="audio/*|video/*|image/*|MIME_type" />
Tip: To specify more than one value, separate the values with a comma (e.g.
<input accept="audio/*,video/*,image/*" />
.
Swift 3
class MyObject: NSObject, NSCoding {
let name : String
let url : String
let desc : String
init(tuple : (String,String,String)){
self.name = tuple.0
self.url = tuple.1
self.desc = tuple.2
}
func getName() -> String {
return name
}
func getURL() -> String{
return url
}
func getDescription() -> String {
return desc
}
func getTuple() -> (String, String, String) {
return (self.name,self.url,self.desc)
}
required init(coder aDecoder: NSCoder) {
self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.url, forKey: "url")
aCoder.encode(self.desc, forKey: "desc")
}
}
to store and retrieve:
func save() {
let data = NSKeyedArchiver.archivedData(withRootObject: object)
UserDefaults.standard.set(data, forKey:"customData" )
}
func get() -> MyObject? {
guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
}
It'd be easier to do your UPDATE first and then run 'SELECT ID FROM INSERTED'.
Take a look at SQL Tips for more info and examples.
Construct both separate queries and joins, then time each of them -- nothing helps more than real-world numbers.
Then even better -- add "EXPLAIN" to the beginning of each query. This will tell you how many subqueries MySQL is using to answer your request for data, and how many rows scanned for each query.
Explanation with an example:
Consider you have a game (iso) image in your computer.
When you run
(mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]
But when you stop
(similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]
And when you do start
(similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]
In this example - The game image is your Docker image and virtual drive is your container.
I'm working with CocoaPods frameworks and in case UIApplication.shared
is unavailable then I use safeAreaInsets
in view's window
:
if #available(iOS 11.0, *) {
let insets = view.window?.safeAreaInsets
let top = insets.top
let bottom = insets.bottom
}
print $input."<hr>".ereg_replace('/&/', ':::', $input);
becomes
print $input."<hr>".preg_replace('/&/', ':::', $input);
More example :
$mytext = ereg_replace('[^A-Za-z0-9_]', '', $mytext );
is changed to
$mytext = preg_replace('/[^A-Za-z0-9_]/', '', $mytext );
Try:
sudo /etc/init.d/mysql reload
or
sudo /etc/init.d/mysql force-reload
That should initiate a reload of the configuration. Make sureyour init.d script supports it though, I don't know what version of MySQL/OS you are using?
My MySQL script contains the following:
'reload'|'force-reload')
log_daemon_msg "Reloading MySQL database server" "mysqld"
$MYADMIN reload
log_end_msg 0
;;
You can explicitly get back Identity columns using SqlServer's OUTPUT clause: Assuming you have an identity/auto-increment column called ID:
$sql='INSERT INTO [xyz].[myTable] (Field1, Field2, Field3) OUTPUT Inserted.ID VALUES (1, 2, '3')';
Note that in Perl DBI you would then execute the INSERT statement, just like it was a SELECT. And capture the output like it was a SELECT
$sth->execute($sql);
@row=$sth->fetchrow_array; #Only 1 val in 1 row returned
print "Inserted ID: ", $row[0], "\n";
Presumably this is preferable because it doesn't require another request.
Wikipedia has the best description
In C++03, the compiler must instantiate a template whenever a fully specified template is encountered in a translation unit. If the template is instantiated with the same types in many translation units, this can dramatically increase compile times. There is no way to prevent this in C++03, so C++11 introduced extern template declarations, analogous to extern data declarations.
C++03 has this syntax to oblige the compiler to instantiate a template:
template class std::vector<MyClass>;
C++11 now provides this syntax:
extern template class std::vector<MyClass>;
which tells the compiler not to instantiate the template in this translation unit.
nonstandard extension used...
Microsoft VC++ used to have a non-standard version of this feature for some years already (in C++03). The compiler warns about that to prevent portability issues with code that needed to compile on different compilers as well.
Look at the sample in the linked page to see that it works roughly the same way. You can expect the message to go away with future versions of MSVC, except of course when using other non-standard compiler extensions at the same time.
The Footer be positioned at the bottom of the page, but not fixed.
CSS
html {
height: 100%;
}
body {
position: relative;
margin: 0;
min-height: 100%;
padding: 0;
}
#header {
background: #595959;
height: 90px;
}
#footer {
position: absolute;
bottom: 0;
width: 100%;
height: 90px;
background-color: #595959;
}
HTML
<html>
<head></head>
<body>
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
</body>
</html>
You can use the negation pseudo-class :not()
against the :last-child
pseudo-class. Being introduced CSS Selectors Level 3, it doesn't work in IE8 or below:
:not(:last-child) { /* styles */ }
this below code work all text please use it:
$des = str_replace('\n',' ',$des);
$des = str_replace('\r',' ',$des);
My way is
$response = curl_exec($ch);
$x = explode("\r\n\r\n", $v, 3);
$header=http_parse_headers($x[0]);
if ($header=['Response Code']==100){ //use the other "header"
$header=http_parse_headers($x[1]);
$body=$x[2];
}else{
$body=$x[1];
}
If needed apply a for loop and remove the explode limit.
There's a bit rough method to do that. If and only if the A set contains some B's element than the call
A.removeAll(B)
will modify the A set. In this situation removeAll will return true (As stated at removeAll docs). But probably you don't want to modify the A set so you may think to act on a copy, like this way:
new HashSet(A).removeAll(B)
and the returning value will be true if the sets are not distinct, that is they have non-empty intersection.
Also see Apache Commons Collections
We have had some fun with the following, interesting to share so:
class RepeatFunction:
def __init__(self,n=1): self.n = n
def __call__(self,Func):
for i in xrange(self.n):
Func()
return Func
#----usage
k = 0
@RepeatFunction(7) #decorator for repeating function
def Job():
global k
print k
k += 1
print '---------'
Job()
Results:
0
1
2
3
4
5
6
---------
7
Basic qustion if you are using generics in your base control. If yes:
lets say we have control:
public class MyComboDropDown : ComboDropDownComon<MyType>
{
public MyComboDropDown() { }
}
MyComboDropDown will not allow to open designer on it and will be not shown in Toolbox. Why? Because base control is not already compiled - when MyComboDropDown is complied. You can modify to this:
public class MyComboDropDown : MyComboDropDownBase
{
public MyComboDropDown() { }
}
public class MyComboDropDownBase : ComboDropDownComon<MyType>
{
}
Than after rebuild, and reset toolbox it should be able to see MyComboDropDown in designer and also in Toolbox
I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed
.
And I finally solved it by using a ssh key
way to authorize myself. I found the EGit offical guide very useful and I configured the ssh
way successfully by refer to the Eclipse SSH Configuration
section in the link provided.
Hope it helps.
Even after installing the sqlserver jar, my maven was trying to fetch the dependecy from maven repository. I then, provided my pom the repository of my local machine and it works fine after that...might be of help for someone.
<repository>
<id>local</id>
<name>local</name>
<url>file://C:/Users/mywindows/.m2/repository</url>
</repository>
The following information is from:
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag
It is very easy to get clean URLs and remove the hashtag from the URL in Angular.
By default, AngularJS will route URLs with a hashtag
For Example:
There are 2 things that need to be done.
Configuring $locationProvider
Setting our base for relative links
$location Service
In Angular, the $location service parses the URL in the address bar and makes changes to your application and vice versa.
I would highly recommend reading through the official Angular $location docs to get a feel for the location service and what it provides.
https://docs.angularjs.org/api/ng/service/$location
$locationProvider and html5Mode
We will do this when defining your Angular application and configuring your routes.
angular.module('noHash', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
controller : mainController
})
.when('/about', {
templateUrl : 'partials/about.html',
controller : mainController
})
.when('/contact', {
templateUrl : 'partials/contact.html',
controller : mainController
});
// use the HTML5 History API
$locationProvider.html5Mode(true); });
What is the HTML5 History API? It is a standardized way to manipulate the browser history using a script. This lets Angular change the routing and URLs of our pages without refreshing the page. For more information on this, here is a good HTML5 History API Article:
http://diveintohtml5.info/history.html
Setting For Relative Links
<base>
in the <head>
of your document. This may be in the
root index.html file of your Angular app. Find the <base>
tag, and
set it to the root URL you'd like for your app.For example: <base href="/">
Fallback for Older Browsers
In Conclusion
If you have an AMD Ryzen processor in your computer you need the following setup requirements to be in place:
Note:There is Hyper-V features... You should enable Windows Hypervisor Platform not Hyper-V. Windows Hypervisor Platform is at the bottom
After conditions done avd x86 work without haxm install
Not the answer for this question
I got this exception when trying to delete a folder where i deleted the file inside.
Example:
createFolder("folder");
createFile("folder/file");
deleteFile("folder/file");
deleteFolder("folder"); // error here
While deleteFile("folder/file");
returned that it was deleted, the folder will only be considered empty after the program restart.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#delete-java.nio.file.Path-
I was getting this error because I was using an older version of angular that wasn't compatible with my code.
Starting from C# 2.0, you can use the nullable generic type Nullable, and in C# there is a shorthand notation the type followed by ?
e.g.
private void Example(int? arg1, int? arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//do something else
}
}
You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');
. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.
You've declared the class Thing
as a non-static inner class. That means it must be associated with an instance of the Hello
class.
In your code, you're trying to create an instance of Thing
from a static context. That is what the compiler is complaining about.
There are a few possible solutions. Which solution to use depends on what you want to achieve.
Move Thing
out of the Hello
class.
Change Thing
to be a static
nested class.
static class Thing
Create an instance of Hello
before creating an instance of Thing
.
public static void main(String[] args)
{
Hello h = new Hello();
Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
}
The last solution (a non-static nested class) would be mandatory if any instance of Thing
depended on an instance of Hello
to be meaningful. For example, if we had:
public class Hello {
public int enormous;
public Hello(int n) {
enormous = n;
}
public class Thing {
public int size;
public Thing(int m) {
if (m > enormous)
size = enormous;
else
size = m;
}
}
...
}
any raw attempt to create an object of class Thing
, as in:
Thing t = new Thing(31);
would be problematic, since there wouldn't be an obvious enormous
value to test 31 against it. An instance h
of the Hello
outer class is necessary to provide this h.enormous
value:
...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...
Because it doesn't mean a Thing
if it doesn't have a Hello
.
For more information on nested/inner classes: Nested Classes (The Java Tutorials)
If you have Java 7 so include the below following snippet within your app-level build.gradle
:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
this.print(false);
I tried this in Chrome, Firefox and IE. It works only in Firefox and IE, it uses the default printer (with default print settings) and only works when I render a PDF (I use Foxit Reader with Safe Reading Mode disabled). Chrome shows the print dialog, also the other browsers when I render an HTML page.
use panTo(x,y).This will help u
The .map
files are for js
and css
(and now ts
too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.
Same for CSS files. Once you take a SASS or LESS file and compile it to CSS, it looks nothing like its original form. If you enable sourcemaps, then you can see the original state of the file, instead of the modified state.
So, to answer you questions in order:
I hope this makes sense.
Go to cmd and type: node "C:\Path\To\File\Sample.js"
Just wanted to put an update. page-break-after
is a legacy property now.
Official page states
This property has been replaced by the break-after property.
other = s or "some default value"
Ok, it must be clarified how the or
operator works. It is a boolean operator, so it works in a boolean context. If the values are not boolean, they are converted to boolean for the purposes of the operator.
Note that the or
operator does not return only True
or False
. Instead, it returns the first operand if the first operand evaluates to true, and it returns the second operand if the first operand evaluates to false.
In this case, the expression x or y
returns x
if it is True
or evaluates to true when converted to boolean. Otherwise, it returns y
. For most cases, this will serve for the very same purpose of C?'s null-coalescing operator, but keep in mind:
42 or "something" # returns 42
0 or "something" # returns "something"
None or "something" # returns "something"
False or "something" # returns "something"
"" or "something" # returns "something"
If you use your variable s
to hold something that is either a reference to the instance of a class or None
(as long as your class does not define members __nonzero__()
and __len__()
), it is secure to use the same semantics as the null-coalescing operator.
In fact, it may even be useful to have this side-effect of Python. Since you know what values evaluates to false, you can use this to trigger the default value without using None
specifically (an error object, for example).
In some languages this behavior is referred to as the Elvis operator.
Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!
Merging typed data structure trees is not trivial, you need to define the precedence, handle incompatible types, define how they will be casted and merged...
So in my opinion, you won't avoid
... pulling them all apart and individually adding in by puts`.
If your question is: Has someone done it for me yet?
Then I think you can have a look at this YAML merging library/tool I revived. (YAML is a superset of JSON), and the principles are applicable to both.
(However, this particular code returns YAML objects, not JSON. Feel free to extend the project and send a PR.)
All these solutions are too long. The base idea is to write the quotient (for example, 5=101) as 100 + 00 + 1 = 101.
public static Point divide(int a, int b) {
if (a < b)
return new Point(0,a);
if (a == b)
return new Point(1,0);
int q = b;
int c = 1;
while (q<<1 < a) {
q <<= 1;
c <<= 1;
}
Point r = divide(a-q, b);
return new Point(c + r.x, r.y);
}
public static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int compare(Point b) {
if (b.x - x != 0) {
return x - b.x;
} else {
return y - b.y;
}
}
@Override
public String toString() {
return " (" + x + " " + y + ") ";
}
}
I will assume that you want a uniformly distributed random number generator like below. Random number in most of programming language including C# and C++ is not properly shuffled before using them. This means that you will get the same number over and over, which isn't really random. To avoid to draw the same number over and over, you need a seed. Typically, ticks in time is ok for this task. Remember that you will get the same number over and over if you are using the same seed every time. So try to use varying seed always. Time is a good source for seed because they chage always.
int GetRandomNumber(int min, int max)
{
Random rand = new Random((int)DateTime.Now.Ticks);
return rand.Next(min, max);
}
if you are looking for random number generator for normal distribution, you might use a Box-Muller transformation. Check the answer by yoyoyoyosef in Random Gaussian Variable Question. Since you want integer, you have to cast double value to integer at the end.
Random rand = new Random(); //reuse this if you are generating many
double u1 = 1.0-rand.NextDouble(); //uniform(0,1] random doubles
double u2 = 1.0-rand.NextDouble();
double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
Math.Sin(2.0 * Math.PI * u2); //random normal(0,1)
double randNormal =
mean + stdDev * randStdNormal; //random normal(mean,stdDev^2)
From the Python PEP 8 -- Style Guide for Python Code:
Descriptive: Naming Styles
The following special forms using leading or trailing underscores are recognized (these can generally be combined with any case convention):
_single_leading_underscore
: weak "internal use" indicator. E.g.from M import *
does not import objects whose name starts with an underscore.
single_trailing_underscore_
: used by convention to avoid conflicts with Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
__double_leading_underscore
: when naming a class attribute, invokes name mangling (inside class FooBar,__boo
becomes_FooBar__boo
; see below).
__double_leading_and_trailing_underscore__
: "magic" objects or attributes that live in user-controlled namespaces. E.g.__init__
,__import__
or__file__
. Never invent such names; only use them as documented.
Note that names with double leading and trailing underscores are essentially reserved for Python itself: "Never invent such names; only use them as documented".
A simple definition would be an HTTP request that acts like a normal method call; i.e., it accepts parameters and returns a structured result, usually XML, that can be deserialized into an object(s).
strcmp will return different values based on the environment it is running(Linux/Windows)!
The reason is the that it has a bug as the bug report says https://bugs.php.net/bug.php?id=53999
Please handle with care!!Thank you.
Both patterns come for the same necessity: Hide from some client code the construction logic of a complex object. But what makes "complex" (or, sometimes, complicate) an object? Mainly, it's due to dependencies, or rather the state of an object composed by more partial states. You can inject dependencies by constructor to set the initial object state, but an object may require a lot of them, some will be in a default initial state (just because we should have learned that set a default dependency to null is not the cleanest way) and some other set to a state driven by some condition. Moreover, there are object properties that are some kind of "oblivious dependencies" but also they can assume optional states.
there are two well known ways to dominate that complexity:
Composition/aggregation: Construct an object, construct its dependent objects, then wire together. Here, a builder can make transparent and flexible the process that determines the rules that lead the construction of component.
Polymorphism: Construction rules are declared directly into subtype definition, so you have a set of rules for each subtype and some condition decides which one among these set of rules apply to construct the object. A factory fits perfectly in this scenario.
Nothing prevents to mix these two approaches. A family of product could abstract object creation done with a builder, a builder could use factories to determine which component object instantiate.
Javascript has an eval()
function for such occasions:
function (varString) {
var myVar = eval(varString);
// .....
}
Edit: Sorry, I think I skimmed the question too quickly. This will only get you the variable, to set it you need
function SetTo5(varString) {
var newValue = 5;
eval(varString + " = " + newValue);
}
or if using a string:
function SetToString(varString) {
var newValue = "string";
eval(varString + " = " + "'" + newValue + "'");
}
But I imagine there is a more appropriate way to accomplish what you're looking for? I don't think eval() is something you really want to use unless there's a great reason for it. eval()
Use draw9patch... included within Android Studio's SDK tools. You can define the stretchable areas of your image. Important parts are constrained and the image doesn't look all warped. A good demo on dra9patch is HERE
Use draw9patch to change your existing splash.png into new_splash.9.png, drag new_splash.9.png into the drawable-hdpi project folder ensure the AndroidManifest and styles.xml are proper as below:
AndroidManifest.xml:
<application
...
android:theme="@style/splashScreenStyle"
>
styles.xml:
<style name="splashScreenStyle" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:windowBackground">@drawable/new_splash</item>
</style>
As far as @joaqin's solution is deprecated, because set_value
method will be removed in a future pandas release, I would mention the other option to add a single item to pandas series, using .at[]
accessor.
>>> import pandas as pd
>>> x = pd.Series()
>>> N = 4
>>> for i in range(N):
... x.at[i] = i**2
It produces the same output.
>>> print(x)
0 0
1 1
2 4
3 9
This may help you find what you're looking for... Batch script loop
My answer is as follows:
@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start
:end
echo var has reached %var%.
pause
exit
The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.
You can also use eval()
to do the same thing.
//A function to call
function needToBeCalled(p1, p2)
{
alert(p1+"="+p2);
}
//A function where needToBeCalled passed as an argument with necessary params
//Here params is comma separated string
function callAnotherFunction(aFunction, params)
{
eval(aFunction + "("+params+")");
}
//A function Call
callAnotherFunction("needToBeCalled", "10,20");
That's it. I was also looking for this solution and tried solutions provided in other answers but finally got it work from above example.
Go to Workbench Edit ? Preferences ? SQL Editor ? DBMS connections read time out : Up to 3000. The error no longer occurred.
Try this:
$objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
I hope you find this helpful:
typeof(IList<T>).IsGenericType == true
typeof(IList<T>).GetGenericTypeDefinition() == typeof(IList<>)
typeof(IList<int>).GetGenericArguments()[0] == typeof(int)
much simpler:
$("selector for element").get(0).scrollIntoView();
if more than one item returns in the selector, the get(0) will get only the first item.
I use lazy unmount: umount -l
(that's a lowercase L
)
Lazy unmount. Detach the filesystem from the filesystem hierarchy now, and cleanup all references to the filesystem as soon as it is not busy anymore. (Requires kernel 2.4.11 or later.)
simple example would be using substring like :
string your_url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path_you_want = your_url .Substring(0, your_url .IndexOf("?"));
Sorting an observable and returning the same object sorted can be done using an extension method. For larger collections watch out for the number of collection changed notifications.
I have updated my code to improve performance (thanks to nawfal) and to handle duplicates which no other answers here do at time of writing. The observable is partitioned into a left sorted half and a right unsorted half, where each time the minimum item (as found in the sorted list) is shifted to the end of the sorted partition from the unsorted. Worst case O(n). Essentially a selection sort (See below for output).
public static void Sort<T>(this ObservableCollection<T> collection)
where T : IComparable<T>, IEquatable<T>
{
List<T> sorted = collection.OrderBy(x => x).ToList();
int ptr = 0;
while (ptr < sorted.Count - 1)
{
if (!collection[ptr].Equals(sorted[ptr]))
{
int idx = search(collection, ptr+1, sorted[ptr]);
collection.Move(idx, ptr);
}
ptr++;
}
}
public static int search<T>(ObservableCollection<T> collection, int startIndex, T other)
{
for (int i = startIndex; i < collection.Count; i++)
{
if (other.Equals(collection[i]))
return i;
}
return -1; // decide how to handle error case
}
usage: Sample with an observer (used a Person class to keep it simple)
public class Person:IComparable<Person>,IEquatable<Person>
{
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Person other)
{
if (this.Age == other.Age) return 0;
return this.Age.CompareTo(other.Age);
}
public override string ToString()
{
return Name + " aged " + Age;
}
public bool Equals(Person other)
{
if (this.Name.Equals(other.Name) && this.Age.Equals(other.Age)) return true;
return false;
}
}
static void Main(string[] args)
{
Console.WriteLine("adding items...");
var observable = new ObservableCollection<Person>()
{
new Person {Name = "Katy", Age = 51},
new Person {Name = "Jack", Age = 12},
new Person {Name = "Bob", Age = 13},
new Person {Name = "Alice", Age = 39},
new Person {Name = "John", Age = 14},
new Person {Name = "Mary", Age = 41},
new Person {Name = "Jane", Age = 20},
new Person {Name = "Jim", Age = 39},
new Person {Name = "Sue", Age = 5},
new Person {Name = "Kim", Age = 19}
};
//what do observers see?
observable.CollectionChanged += (sender, e) =>
{
Console.WriteLine(
e.OldItems[0] + " move from " + e.OldStartingIndex + " to " + e.NewStartingIndex);
int i = 0;
foreach (var person in sender as ObservableCollection<Person>)
{
if (i == e.NewStartingIndex)
{
Console.Write("(" + (person as Person).Age + "),");
}
else
{
Console.Write((person as Person).Age + ",");
}
i++;
}
Console.WriteLine();
};
Details of sorting progress showing how the collection is pivoted:
Sue aged 5 move from 8 to 0
(5),51,12,13,39,14,41,20,39,19,
Jack aged 12 move from 2 to 1
5,(12),51,13,39,14,41,20,39,19,
Bob aged 13 move from 3 to 2
5,12,(13),51,39,14,41,20,39,19,
John aged 14 move from 5 to 3
5,12,13,(14),51,39,41,20,39,19,
Kim aged 19 move from 9 to 4
5,12,13,14,(19),51,39,41,20,39,
Jane aged 20 move from 8 to 5
5,12,13,14,19,(20),51,39,41,39,
Alice aged 39 move from 7 to 6
5,12,13,14,19,20,(39),51,41,39,
Jim aged 39 move from 9 to 7
5,12,13,14,19,20,39,(39),51,41,
Mary aged 41 move from 9 to 8
5,12,13,14,19,20,39,39,(41),51,
The Person class implements both IComparable and IEquatable the latter is used to minimise the changes to the collection so as to reduce the number of change notifications raised
To return an ObservableCollection, call .ToObservableCollection on *sortedOC* using e.g. [this implementation][1].
**** orig answer - this creates a new collection **** You can use linq as the doSort method below illustrates. A quick code snippet: produces
3:xey 6:fty 7:aaa
Alternatively you could use an extension method on the collection itself
var sortedOC = _collection.OrderBy(i => i.Key);
private void doSort()
{
ObservableCollection<Pair<ushort, string>> _collection =
new ObservableCollection<Pair<ushort, string>>();
_collection.Add(new Pair<ushort,string>(7,"aaa"));
_collection.Add(new Pair<ushort, string>(3, "xey"));
_collection.Add(new Pair<ushort, string>(6, "fty"));
var sortedOC = from item in _collection
orderby item.Key
select item;
foreach (var i in sortedOC)
{
Debug.WriteLine(i);
}
}
public class Pair<TKey, TValue>
{
private TKey _key;
public TKey Key
{
get { return _key; }
set { _key = value; }
}
private TValue _value;
public TValue Value
{
get { return _value; }
set { _value = value; }
}
public Pair(TKey key, TValue value)
{
_key = key;
_value = value;
}
public override string ToString()
{
return this.Key + ":" + this.Value;
}
}
Do what Mehrdad says - or use the url helper from an HtmlHelper
extension method like Stephen Walther describes here and make your own extension method which can be used to render all of your links.
Then it will be easy to render all links as buttons/anchors or whichever you prefer - and, most importantly, you can change your mind later when you find out that you actually prefer some other way of making your links.
To get rid of error:
Type '"text"' is not assignable to type '"json"'.
Use
responseType: 'text' as 'json'
import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
return this.http
.post<string>(
this.baseUrl + '/Tickets/getTicket',
JSON.stringify(value),
{ headers, responseType: 'text' as 'json' }
)
.map(res => {
return res;
})
.catch(this.handleError);
You can use the Mock.call_args_list
attribute to compare parameters to previous method calls. That in conjunction with Mock.call_count
attribute should give you full control.
If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator
.
This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator")
can be overriden via command line options and isn't as type safe as java.io.File.separator
.
The last one, java.nio.file.FileSystems.getDefault().getSeparator();
was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.
So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.
If you are invoking foobarfunc
with resolution scope operator (::
), then you are calling it statically, e.g. on the class level instead of the instance level, thus you are using $this
when not in object context. $this
does not exist in class context.
If you enable E_STRICT
, PHP will raise a Notice about this:
Strict Standards:
Non-static method foobar::foobarfunc() should not be called statically
Do this instead
$fb = new foobar;
echo $fb->foobarfunc();
On a sidenote, I suggest not to use global
inside your classes. If you need something from outside inside your class, pass it through the constructor. This is called Dependency Injection and it will make your code much more maintainable and less dependant on outside things.
It will be faster because it doesnt have to wait for locks
I'm loading the PDF with jQuery ajax into browser cache. Then I create embedded element with data already in browser cache. I guess it will work with iframe too.
var url = "http://example.com/my.pdf";
// show spinner
$.mobile.showPageLoadingMsg('b', note, false);
$.ajax({
url: url,
cache: true,
mimeType: 'application/pdf',
success: function () {
// display cached data
$(scroller).append('<embed type="application/pdf" src="' + url + '" />');
// hide spinner
$.mobile.hidePageLoadingMsg();
}
});
You have to set your http headers correctly as well.
HttpContext.Response.Expires = 1;
HttpContext.Response.Cache.SetNoServerCaching();
HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);
HttpContext.Response.CacheControl = "Private";
You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?
Its very easy just do the following:
add the following line in your manifest.json
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
Now you are free to load jQuery directly from url
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
Source: google doc
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
In your JBoss lib Directory:
maybe I'd go by this.
SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable
I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.
Hope that helps.
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
You could compile and link in one command:
gcc file1.c file2.c -o myprogram
And run with:
./myprogram
But to answer the question as asked, simply pass the object files to gcc
:
gcc file1.o file2.o -o myprogram
I'm not sure what causes your problem put this code works perfectly for me. I think it has something to do with using the correct xml namespace (xmlns
). I'm not sure if using android.support.design without xml namespace attribute is supported. Or it has something to do with the textColorHint
attribute you are using on the EditText itself.
Layout:
<android.support.design.widget.TextInputLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
app:hintTextAppearance="@style/GreenTextInputLayout">
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="test"
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
Style:
<style name="GreenTextInputLayout" parent="@android:style/TextAppearance">
<item name="android:textColor">#00FF00</item>
</style>
There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.
There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.
%find . -type f | wc -l
791887
%time git add .
git add . 6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status 0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G .
%cd .git
%du -sh .
7.9G .
As other have said C maps in row order
#include <stdio.h>
int main(int argc, char **argv) {
int i, j, k;
int arr[5][3];
int *arr2 = (int*)arr;
for (k=0; k<15; k++) {
arr2[k] = k;
printf("arr[%d] = %2d\n", k, arr2[k]);
}
for (i=0; i<5; i++) {
for (j=0; j< 3; j++) {
printf("arr2[%d][%d] = %2d\n", i, j ,arr[i][j]);
}
}
}
Output:
arr[0] = 0
arr[1] = 1
arr[2] = 2
arr[3] = 3
arr[4] = 4
arr[5] = 5
arr[6] = 6
arr[7] = 7
arr[8] = 8
arr[9] = 9
arr[10] = 10
arr[11] = 11
arr[12] = 12
arr[13] = 13
arr[14] = 14
arr2[0][0] = 0
arr2[0][1] = 1
arr2[0][2] = 2
arr2[1][0] = 3
arr2[1][1] = 4
arr2[1][2] = 5
arr2[2][0] = 6
arr2[2][1] = 7
arr2[2][2] = 8
arr2[3][0] = 9
arr2[3][1] = 10
arr2[3][2] = 11
arr2[4][0] = 12
arr2[4][1] = 13
arr2[4][2] = 14
The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.
Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.
If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/
is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/
or http://s3-external-1.amazonaws.com/bucket/
.¹
The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].
S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com
. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.
If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.
However... the two endpoints do not offer the same functionality.
Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.
Choose the correct type of endpoint (REST or web site) for your application:
http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff
¹ s3-external-1.amazonaws.com
has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com
. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2
had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1
so s3-external-2
appears to have no purpose except backwards-compatibility.
Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:
CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;
In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.