Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:
public function foo(Request $request){
$bodyContent = $request->getContent();
}
You seem to be aware already, but I'll just restate it anyway; It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details. That said, there are cases where it makes sense. If you use inheritance, you can see a superclass as providing an interface for the subclass. So here, you would have to test the protected method (But never a private one). The solution to this, is to create a subclass for testing purpose, and use this to expose the methods. Eg.:
class Foo {
protected function stuff() {
// secret stuff, you want to test
}
}
class SubFoo extends Foo {
public function exposedStuff() {
return $this->stuff();
}
}
Note that you can always replace inheritance with composition. When testing code, it's usually a lot easier to deal with code that uses this pattern, so you may want to consider that option.
Following command will execute exactly testSaveAndDrop
test.
phpunit --filter '/::testSaveAndDrop$/' escalation/EscalationGroupTest.php
If you're running on PHP 5.5+, you can use ::class
resolution to obtain the name of the class with expectException
/setExpectedException
. This provides several benefits:
string
so it will work with any version of PHPUnit.Example:
namespace \My\Cool\Package;
class AuthTest extends \PHPUnit_Framework_TestCase
{
public function testLoginFailsForWrongPassword()
{
$this->expectException(WrongPasswordException::class);
Auth::login('Bob', 'wrong');
}
}
PHP compiles
WrongPasswordException::class
into
"\My\Cool\Package\WrongPasswordException"
without PHPUnit being the wiser.
Note: PHPUnit 5.2 introduced
expectException
as a replacement forsetExpectedException
.
I had to modify source code for this code to work so you need to add URL for this forked repos to composer for this will work
class TestCase extends \PHPUnit_Framework_TestCase
{
/**
* Save last response
* @var Response|null A Response instance
*/
static $lastResponse;
/**
* Modify to save response
*
* @param string $method
* @param string $uri
* @param array $parameters
* @param array $files
* @param array $server
* @param string $content
* @param bool $changeHistory
* @return \Illuminate\Http\Response
*/
final public function call(
$method,
$uri,
$parameters = [],
$files = [],
$server = [],
$content = null,
$changeHistory = true
) {
$response = parent::call($method, $uri, $parameters, $files, $server, $content, $changeHistory);
static::$lastResponse = $this->client->getResponse();
return $response;
}
/**
* Modify message to add response text
*
* @param mixed $value
* @param PHPUnit_Framework_Constraint $constraint
* @param string $message
* @since Method available since Release 3.0.0
*/
final public static function assertThat($value, PHPUnit_Framework_Constraint $constraint, $message = '')
{
$message .= PHP_EOL . static::$lastResponse . PHP_EOL;
parent::assertThat($value, $constraint, $message);
}
}
You just need flex:1
; It will fix issue for the IE11. I second Odisseas. Additionally assign 100% height to html,body elements.
CSS changes:
html, body{
height:100%;
}
body {
border: red 1px solid;
min-height: 100vh;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-ms-flex-direction: column;
-webkit-flex-direction: column;
flex-direction: column;
}
header {
background: #23bcfc;
}
main {
background: #87ccfc;
-ms-flex: 1;
-webkit-flex: 1;
flex: 1;
}
footer {
background: #dd55dd;
}
working url: http://jsfiddle.net/3tpuryso/13/
Maybe you are looking for something like this?
>>> class MyTest:
def __init__ (self):
self.value = 3
>>> myobj = MyTest()
>>> myobj.__dict__
{'value': 3}
Please read the example in rfc6749 sec 7.1 first.
The bearer token is a type of access token, which does NOT require PoP(proof-of-possession) mechanism.
PoP means kind of multi-factor authentication to make access token more secure. ref
Proof-of-Possession refers to Cryptographic methods that mitigate the risk of Security Tokens being stolen and used by an attacker. In contrast to 'Bearer Tokens', where mere possession of the Security Token allows the attacker to use it, a PoP Security Token cannot be so easily used - the attacker MUST have both the token itself and access to some key associated with the token (which is why they are sometimes referred to 'Holder-of-Key' (HoK) tokens).
Maybe it's not the case, but I would say,
BTW, there's a draft of "OAuth 2.0 Proof-of-Possession (PoP) Security Architecture" now.
From here:
-Xmn : the size of the heap for the young generation
Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".
And a more "official" source from IBM:
-Xmn
Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.
A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]
A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.
From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.
Well, if one needs a long whitespace in the beginning of one line only out of the whole paragraph, then this may be a solution:
<span style='display:inline-block;height:1em;width:4em;'> </span>
If that is too much to write or one needs such tabs in many places, then you can do this
<span class='tab'> </span>
Then include this into CSS:
span.tab {display:inline-block;height:1em;width:4em;}
Please note that if you have multiple application.properties
files throughout your codebase, then try adding your value to the parent project's property file.
You can check your project's pom.xml
file to identify what the parent project of your current project is.
Alternatively, try using environment.getProperty()
instead of @Value
.
I managed to connect to postgres with SQL Developer. I downloaded postgres jdbc driver and saved it in a folder. I run SQL Developer -> Tools -> Preferences -> Search -> JDBC I defined postgres jdbc driver for the Database and Data Modeler (optional).
This is the trick. When creating new connection define Hostname like localhost/crm? where crm is the database name. Test the connection, works fine.
Here's some code I use to add dynamic favicon support to Opera, Firefox and Chrome. I couldn't get IE or Safari working though. Basically Chrome allows dynamic favicons, but it only updates them when the page's location (or an iframe
etc in it) changes as far as I can tell:
var IE = navigator.userAgent.indexOf("MSIE")!=-1
var favicon = {
change: function(iconURL) {
if (arguments.length == 2) {
document.title = optionalDocTitle}
this.addLink(iconURL, "icon")
this.addLink(iconURL, "shortcut icon")
// Google Chrome HACK - whenever an IFrame changes location
// (even to about:blank), it updates the favicon for some reason
// It doesn't work on Safari at all though :-(
if (!IE) { // Disable the IE "click" sound
if (!window.__IFrame) {
__IFrame = document.createElement('iframe')
var s = __IFrame.style
s.height = s.width = s.left = s.top = s.border = 0
s.position = 'absolute'
s.visibility = 'hidden'
document.body.appendChild(__IFrame)}
__IFrame.src = 'about:blank'}},
addLink: function(iconURL, relValue) {
var link = document.createElement("link")
link.type = "image/x-icon"
link.rel = relValue
link.href = iconURL
this.removeLinkIfExists(relValue)
this.docHead.appendChild(link)},
removeLinkIfExists: function(relValue) {
var links = this.docHead.getElementsByTagName("link");
for (var i=0; i<links.length; i++) {
var link = links[i]
if (link.type == "image/x-icon" && link.rel == relValue) {
this.docHead.removeChild(link)
return}}}, // Assuming only one match at most.
docHead: document.getElementsByTagName("head")[0]}
To change favicons, just go favicon.change("ICON URL")
using the above.
(credits to http://softwareas.com/dynamic-favicons for the code I based this on.)
You can find a list of formatting escapes on this page.
%d
is a signed integer, while %u
is an unsigned integer. Pointers (when treated as numbers) are usually non-negative.
If you actually want to display a pointer, use the %p
format specifier.
Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!
for (int i = 0; i < 3; i++) {
LinearLayout linearDummy = new LinearLayout(getActivity());
linearDummy.setOrientation(LinearLayout.VERTICAL);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();
} else {
linearDummy.setId(View.generateViewId());
}
fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();
xNumberLinear.addView(linearDummy);
}
On MacOS
(I have Mojave/ 10.14, git
version 2.7.1), use bindfs
.
brew install bindfs
cd /path/to/git_controlled_dir
mkdir local_copy_dir
bindfs </full/path/to/source_dir> </full/path/to/local_copy_dir>
It's been hinted by other comments, but not clearly provided in other answers. Hopefully this saves someone some time.
This error is coming only for your PHP version v7.0. you can avoid these using PHP v5.0 else
use it
mysqli_connect("localhost","root","")
i made only mysqli from mysql
you can use myfaces tomahawk component
http://myfaces.apache.org/tomahawk-project/tomahawk12/tagdoc/t_div.html
try this code ['12','34','35','231']*","
will give you result "12,34,35,231"
I hope this is the result you, let me know
The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream
. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
If you are not sure that you have not multiple minimum values, I would suggest:
d = {320:1, 321:0, 322:3, 323:0}
print ', '.join(str(key) for min_value in (min(d.values()),) for key in d if d[key]==min_value)
"""Output:
321, 323
"""
There are several ways to perform HTTP GET
and POST
requests:
Available in: .NET Framework 4.5+
, .NET Standard 1.1+
, .NET Core 1.0+
.
It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.
using System.Net.Http;
It is recommended to instantiate one HttpClient
for your application's lifetime and share it unless you have a specific reason not to.
private static readonly HttpClient client = new HttpClient();
See HttpClientFactory
for a dependency injection solution.
POST
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
GET
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
POST
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
request.AddHeader("header", "value");
request.AddFile("file", path);
var response = client.Post(request);
var content = response.Content; // Raw content as string
var response2 = client.Post<Person>(request);
var name = response2.Data.Name;
It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.
using Flurl.Http;
POST
var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();
GET
var responseString = await "http://www.example.com/recepticle.aspx"
.GetStringAsync();
Available in: .NET Framework 1.1+
, .NET Standard 2.0+
, .NET Core 1.0+
. In .NET Core, it is mostly for compatibility -- it wraps HttpClient
, is less performant, and won't get new features.
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
POST
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
GET
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
This is a wrapper around HttpWebRequest
. Compare with HttpClient
.
Available in: .NET Framework 1.1+
, NET Standard 2.0+
, .NET Core 2.0+
using System.Net;
using System.Collections.Specialized;
POST
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}
GET
using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
If anyone else is having a nullptr on the searchview variable, I found out that the item setup is a tiny bit different:
old:
android:showAsAction="ifRoom"
android:actionViewClass="android.widget.SearchView"
new:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="androidx.appcompat.widget.SearchView"
pre-android x:
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
For more information, it's updated documentation is located here.
I had an activity with theme <android:theme="@android:style/Theme.Dialog">
used for showing dialog in my appWidget and i had same problem
i solved this error by changing activity code like below:
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_AppCompat_Dialog); //this line i added
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialog);
}
In short, yes.
Suppose we are on a 32-bit machine.
If it is little endian, the x
in the memory will be something like:
higher memory
----->
+----+----+----+----+
|0x01|0x00|0x00|0x00|
+----+----+----+----+
A
|
&x
so (char*)(&x) == 1
, and *y+48 == '1'
.
If it is big endian, it will be:
+----+----+----+----+
|0x00|0x00|0x00|0x01|
+----+----+----+----+
A
|
&x
so this one will be '0'
.
Generally:
git log -n
will show you the last n
commit messages
More elegantly - if you want a quick overview of your commits
git log --oneline -n
This will Show just the first line of the last n
commit messages.
You can save this as a git alias or a shell alias with a shorter command. I've got it in my shell as glog
, for example, and I can see my last 10 commit messages with glog -10
.
Firebase provides some good features like real time change reflection , easy integration of authentication mechanism , and lots of other built-in features for rapid web development. Firebase, really makes Web development so simple that never exists. Firebase database is a fork of MongoDB.
What's the advantage of using Firebase over MongoDB?
You can take advantage of all built-in features of Firebase over MongoDB.
echo "Hello MY name is SUJIT " | sed 's/./\L&/g'
Output:
hello my name is sujit
For accessing the elements of a list you need to use the square brackets ([]
) and not the parenthesis (()
).
Instead of:
print wordlists(len(words))
you need to use:
print worldlists[len(words)]
And instead of:
(wordlists(len(words))).append(words)
you need to use:
worldlists[len(words)].append(words)
You could write it like this:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
Simple code for reading file in JAVA:
import java.io.*;
class ReadData
{
public static void main(String args[])
{
FileReader fr = new FileReader(new File("<put your file path here>"));
while(true)
{
int n=fr.read();
if(n>-1)
{
char ch=(char)fr.read();
System.out.print(ch);
}
}
}
}
Just a guess, but I think with the SYSTEM_ALERT_WINDOW permission (displayed as "Draw over other apps", see here) it could be possible: display your app as a fullscreen, system alert type window. This way it will hide any other apps, even the homescreen so if you press Home, it won't really be disabled, just without any visible effect.
MX Player has this permission declared, and Facebook Messenger has it too for displaying "chat heads" over anything - so it might be the solution.
Update (added from my comments): Next, use SYSTEM_UI_FLAG_HIDE_NAVIGATION in conjunction with capturing touch events/using OnSystemUiVisibilityChangeListener to override the default behaviour (navbar appearing on touch). Also, since you said exit immersive gesture does not work, you could try setting SYSTEM_UI_FLAG_IMMERSIVE_STICKY too (with SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION).
A little editing about the code of Schnalle
<?php
$ids = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($ids)-1, '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN(' . $inQuery . ')'
);
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
?>
//implode(',', array_fill(0, count($ids)-1), '?'));
//'?' this should be inside the array_fill
//$stmt->bindValue(($k+1), $in);
// instead of $in, it should be $id
Solution to this problem is connected with what @Pace has written in his answer. However, it doesn't explain everything so, if you don't mind, I'll write it by myself.
SOLUTION:
Adding this line:
///<reference path="./../../../typings/globals/jasmine/index.d.ts"/>
at the beginning of hero.spec.ts
file fixes problem. Path leads to typings
folder (where all typings are stored).
To install typings you need to create typings.json
file in root of your project with following content:
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160807145350"
}
}
And run typings install
(where typings
is NPM package).
You would usually do something like this:
while ( resultSet.next() ) {
// Read the next item
resultSet.getString("columnName");
}
If you want to report an empty set, add a variable counting the items read. If you only need to read a single item, then your code is adequate.
It answers a little more than the OP is expecting... But I hope it could help some one at least.
If you want to execute a ICommand
whenever the SelectedItem
changed, you can bind a command on an event and the use of a property SelectedItem
in the ViewModel
isn't needed anymore.
To do so:
1- Add reference to System.Windows.Interactivity
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
2- Bind the command to the event SelectedItemChanged
<TreeView x:Name="myTreeView" Margin="1"
ItemsSource="{Binding Directories}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedItemChanged">
<i:InvokeCommandAction Command="{Binding SomeCommand}"
CommandParameter="
{Binding ElementName=myTreeView
,Path=SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TreeView.ItemTemplate>
<!-- ... -->
</TreeView.ItemTemplate>
</TreeView>
Cookies and Sessions are used to store information. Cookies are only stored on the client-side machine, while sessions get stored on the client as well as a server.
Session
A session creates a file in a temporary directory on the server where registered session variables and their values are stored. This data will be available to all pages on the site during that visit.
A session ends when the user closes the browser or after leaving the site, the server will terminate the session after a predetermined period of time, commonly 30 minutes duration.
Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purposes. The server script sends a set of cookies to the browser. For example name, age, or identification number, etc. The browser stores this information on a local machine for future use.
When the next time the browser sends any request to the web server then it sends those cookies information to the server and the server uses that information to identify the user.
try the +
symbol:
It is Adjacent sibling combinator. It combines two sequences of simple selectors having the same parent and the second one must come IMMEDIATELY after the first.
As such:
input[type="radio"]:checked+label{ font-weight: bold; }
//a label that immediately follows an input of type radio that is checked
works very nicely for the following markup:
<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" type="radio" name="rad"/><label for="rad2">Radio 2</label>
... and it will work for any structure, with or without divs etc as long as the label follows the radio input.
Example:
input[type="radio"]:checked+label { font-weight: bold; }
_x000D_
<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>_x000D_
<input id="rad2" type="radio" name="rad"/><label for="rad2">Radio 2</label>
_x000D_
I would seriously consider the use of Boost, particularly boost::posix_time::ptime and boost::posix_time::time_duration (at http://www.boost.org/doc/libs/1_38_0/doc/html/date_time/posix_time.html).
It's cross-platform, easy to use, and in my experience provides the highest level of time resolution an operating system provides. Possibly also very important; it provides some very nice IO operators.
To use it to calculate the difference in program execution (to microseconds; probably overkill), it would look something like this [browser written, not tested]:
ptime time_start(microsec_clock::local_time());
//... execution goes here ...
ptime time_end(microsec_clock::local_time());
time_duration duration(time_end - time_start);
cout << duration << '\n';
OK - all answers provided above are correct to some extend, but did not resolve this issue for me. I'm using Xcode5.
There are lots of threads around this general error but from what I read this is a bug in Xcode dating back to 3.x versions that can randomly create conflicts with your Keychain.
I was able to resolve this by doing the following:
Open Xcode -> preferences -> Accounts: delete your developer account
Open Keychain: Select Keys, delete all iOS keys; Select My Certificates, delete all iPhone certificates
Navigate to '/Users//Library/MobileDevice/Provisioning Profiles', delete all files (this is where Xcode stores mobile profiles)
Open Xcode -> preferences -> Accounts: re-add your developer account
Navigate to Project properties, Target, General Tab and you should see the following
Click 'Revoke and Request' (I tried this, it may take a few min) or 'Import Developer Profile' (or download from Apple developer portal and import this way, should be faster..)
FINALLY: you can go over to Build Settings and set 'Provisioning Profile' and 'Signing Settings' as described by everyone here..
Doing this and only this resolved this error for me.
What is currentWorksheet
? It works if you use the built-in ActiveSheet
.
dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
I suppose you want form based authentication using deployment descriptors and j_security_check
.
You can also do this in JSF by just using the same predefinied field names j_username
and j_password
as demonstrated in the tutorial.
E.g.
<form action="j_security_check" method="post">
<h:outputLabel for="j_username" value="Username" />
<h:inputText id="j_username" />
<br />
<h:outputLabel for="j_password" value="Password" />
<h:inputSecret id="j_password" />
<br />
<h:commandButton value="Login" />
</form>
You could do lazy loading in the User
getter to check if the User
is already logged in and if not, then check if the Principal
is present in the request and if so, then get the User
associated with j_username
.
package com.stackoverflow.q2206911;
import java.io.IOException;
import java.security.Principal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
@ManagedBean
@SessionScoped
public class Auth {
private User user; // The JPA entity.
@EJB
private UserService userService;
public User getUser() {
if (user == null) {
Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
if (principal != null) {
user = userService.find(principal.getName()); // Find User by j_username.
}
}
return user;
}
}
The User
is obviously accessible in JSF EL by #{auth.user}
.
To logout do a HttpServletRequest#logout()
(and set User
to null!). You can get a handle of the HttpServletRequest
in JSF by ExternalContext#getRequest()
. You can also just invalidate the session altogether.
public String logout() {
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
return "login?faces-redirect=true";
}
For the remnant (defining users, roles and constraints in deployment descriptor and realm), just follow the Java EE 6 tutorial and the servletcontainer documentation the usual way.
Update: you can also use the new Servlet 3.0 HttpServletRequest#login()
to do a programmatic login instead of using j_security_check
which may not per-se be reachable by a dispatcher in some servletcontainers. In this case you can use a fullworthy JSF form and a bean with username
and password
properties and a login
method which look like this:
<h:form>
<h:outputLabel for="username" value="Username" />
<h:inputText id="username" value="#{auth.username}" required="true" />
<h:message for="username" />
<br />
<h:outputLabel for="password" value="Password" />
<h:inputSecret id="password" value="#{auth.password}" required="true" />
<h:message for="password" />
<br />
<h:commandButton value="Login" action="#{auth.login}" />
<h:messages globalOnly="true" />
</h:form>
And this view scoped managed bean which also remembers the initially requested page:
@ManagedBean
@ViewScoped
public class Auth {
private String username;
private String password;
private String originalURL;
@PostConstruct
public void init() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
if (originalURL == null) {
originalURL = externalContext.getRequestContextPath() + "/home.xhtml";
} else {
String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);
if (originalQuery != null) {
originalURL += "?" + originalQuery;
}
}
}
@EJB
private UserService userService;
public void login() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
try {
request.login(username, password);
User user = userService.find(username, password);
externalContext.getSessionMap().put("user", user);
externalContext.redirect(originalURL);
} catch (ServletException e) {
// Handle unknown username/password in request.login().
context.addMessage(null, new FacesMessage("Unknown login"));
}
}
public void logout() throws IOException {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
externalContext.redirect(externalContext.getRequestContextPath() + "/login.xhtml");
}
// Getters/setters for username and password.
}
This way the User
is accessible in JSF EL by #{user}
.
Complementing the existing answers, as these commands are recurrent we can do it in a row. Given we are in the feature branch:
git checkout master && git pull && git checkout - && git merge -
Or add them in an alias:
alias merge_with_master="git checkout master && git pull && git checkout - && git merge -"
Great answers for GNU environments above and below...
But... what if you're not running on an OS? (or a PC for that matter, or you need to time your timer interrupts themselves?) Here's a solution that uses the x86 CPU timestamp counter directly... Not because this is good practice, or should be done, ever, when running under an OS...
rdtsc.c:
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned long long int64;
static __inline__ int64 getticks(void)
{
unsigned a, d;
asm volatile("rdtsc" : "=a" (a), "=d" (d));
return (((int64)a) | (((int64)d) << 32));
}
int main(){
int64 tick,tick1;
unsigned time=0,mt;
// mt is the divisor to give microseconds
FILE *pf;
int i,r,l,n=0;
char s[100];
// time how long it takes to get the divisors, as a test
tick = getticks();
// get the divisors - todo: for max performance this can
// output a new binary or library with these values hardcoded
// for the relevant CPU - if you use the equivalent assembler for
// that CPU
pf = fopen("/proc/cpuinfo","r");
do {
r=fscanf(pf,"%s",&s[0]);
if (r<0) {
n=5; break;
} else if (n==0) {
if (strcmp("MHz",s)==0) n=1;
} else if (n==1) {
if (strcmp(":",s)==0) n=2;
} else if (n==2) {
n=3;
};
} while (n<3);
fclose(pf);
s[9]=(char)0;
strcpy(&s[4],&s[5]);
mt=atoi(s);
printf("#define mt %u // (%s Hz) hardcode this for your a CPU-specific binary ;-)\n",mt,s);
tick1 = getticks();
time = (unsigned)((tick1-tick)/mt);
printf("%u ms\n",time);
// time the duration of sleep(1) - plus overheads ;-)
tick = getticks();
sleep(1);
tick1 = getticks();
time = (unsigned)((tick1-tick)/mt);
printf("%u ms\n",time);
return 0;
}
compile and run with
$ gcc rdtsc.c -o rdtsc && ./rdtsc
It reads the divisor for your CPU from /proc/cpuinfo and shows how long it took to read that in microseconds, as well as how long it takes to execute sleep(1) in microseconds... Assuming the Mhz rating in /proc/cpuinfo always contains 3 decimal places :-o
In terms of what you are doing with jQuery, my understanding is that you can chain functions like you have and the inner ones have access to variables from the outer ones. So is your ShowDialog(x) function contains these other functions, you can re-use the x variable within them and it will be taken as a reference to the parameter from the outer function.
I agree with mausch, you should really look at using POST for these actions, which will add a <form>
tag around each element, but make the chances of an automated script or tool triggering the Cancel event much less likely. The Change action can remain as is because it (presumably just opens an edit form).
Here are some tips on working with float and decimals.
0.1 x 10 = 1. Seems reasonable, but at computer level you as developer should handle that:
At any programming language (this was tested with Delphi, VBScript, Visual Basic, JavaScript and now with Java/Android):
double total = 0.0;
// do 10 adds of 10 cents
for (int i = 0; i < 10; i++) {
total += 0.1; // adds 10 cents
}
Log.d("round problems?", "current total: " + total);
// looks like total equals to 1.0, don't?
// now, do reverse
for (int i = 0; i < 10; i++) {
total -= 0.1; // removes 10 cents
}
// looks like total equals to 0.0, don't?
Log.d("round problems?", "current total: " + total);
if (total == 0.0) {
Log.d("round problems?", "is total equal to ZERO? YES, of course!!");
} else {
Log.d("round problems?", "is total equal to ZERO? No...");
// so be careful comparing equality in this cases!!!
}
OUTPUT:
round problems?: current total: 0.9999999999999999
round problems?: current total: 2.7755575615628914E-17
round problems?: is total equal to ZERO? No...
Right click in Project / Clean
That always works for me
__main__.py
is used for python programs in zip files. The __main__.py
file will be executed when the zip file in run. For example, if the zip file was as such:
test.zip
__main__.py
and the contents of __main__.py
was
import sys
print "hello %s" % sys.argv[1]
Then if we were to run python test.zip world
we would get hello world
out.
So the __main__.py
file run when python is called on a zip file.
Look at:
man 3 backtrace
And:
#include <exeinfo.h>
int backtrace(void **buffer, int size);
These are GNU extensions.
git reset
does know five "modes": soft, mixed, hard, merge and keep. I will start with the first three, since these are the modes you'll usually encounter. After that you'll find a nice little a bonus, so stay tuned.
When using git reset --soft HEAD~1
you will remove the last commit from the current branch, but the file changes will stay in your working tree. Also the changes will stay on your index, so following with a git commit
will create a commit with the exact same changes as the commit you "removed" before.
This is the default mode and quite similar to soft. When "removing" a commit with git reset HEAD~1
you will still keep the changes in your working tree but not on the index; so if you want to "redo" the commit, you will have to add the changes (git add
) before commiting.
When using git reset --hard HEAD~1
you will lose all uncommited changes in addition to the changes introduced in the last commit. The changes won't stay in your working tree so doing a git status
command will tell you that you don't have any changes in your repository.
Tread carefully with this one. If you accidentally remove uncommited changes which were never tracked by git
(speak: committed or at least added to the index), you have no way of getting them back using git
.
git reset --keep HEAD~1
is an interesting and useful one. It only resets the files which are different between the current HEAD
and the given commit. It aborts the reset if one or more of these files has uncommited changes. It basically acts as a safer version of hard
.
You can read more about that in the git reset documentation.
Note
When doing git reset
to remove a commit the commit isn't really lost, there just is no reference pointing to it or any of it's children. You can still recover a commit which was "deleted" with git reset
by finding it's SHA-1 key, for example with a command such as git reflog
.
Updated Answer
jQuery changed the location of where events are stored in 1.8. Now you know why it is such a bad idea to mess around with internal APIs :)
The new internal API to access to events for a DOM object is available through the global jQuery object, and not tied to each instance, and it takes a DOM element as the first parameter, and a key ("events" for us) as the second parameter.
jQuery._data(<DOM element>, "events");
So here's the modified code for jQuery 1.8.
// [name] is the name of the event "click", "mouseover", ..
// same as you'd pass it to bind()
// [fn] is the handler function
$.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.on(name, fn);
// Thanks to a comment by @Martin, adding support for
// namespaced events too.
this.each(function() {
var handlers = $._data(this, 'events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var handler = handlers.pop();
// move it at the beginning
handlers.splice(0, 0, handler);
});
};
And here's a playground.
Original Answer
As @Sean has discovered, jQuery exposes all event handlers through an element's data
interface. Specifically element.data('events')
. Using this you could always write a simple plugin whereby you could insert any event handler at a specific position.
Here's a simple plugin that does just that to insert a handler at the beginning of the list. You can easily extend this to insert an item at any given position. It's just array manipulation. But since I haven't seen jQuery's source and don't want to miss out on any jQuery magic from happening, I normally add the handler using bind
first, and then reshuffle the array.
// [name] is the name of the event "click", "mouseover", ..
// same as you'd pass it to bind()
// [fn] is the handler function
$.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.bind(name, fn);
// Thanks to a comment by @Martin, adding support for
// namespaced events too.
var handlers = this.data('events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var handler = handlers.pop();
// move it at the beginning
handlers.splice(0, 0, handler);
};
So for example, for this markup it would work as (example here):
<div id="me">..</div>
$("#me").click(function() { alert("1"); });
$("#me").click(function() { alert("2"); });
$("#me").bindFirst('click', function() { alert("3"); });
$("#me").click(); // alerts - 3, then 1, then 2
However, since .data('events')
is not part of their public API as far as I know, an update to jQuery could break your code if the underlying representation of attached events changes from an array to something else, for example.
Disclaimer: Since anything is possible :), here's your solution, but I would still err on the side of refactoring your existing code, as just trying to remember the order in which these items were attached can soon get out of hand as you keep adding more and more of these ordered events.
Hi I'm also relatively new but I can give you basic help.
UPDATE 12.01.2016:
The bold line is the current branch.
You can also just double click a branch to use checkout.
And here some helpful links:
The method jQuery (v1.10) uses to find this is:
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
That is:
window.pageXOffset
first and uses that if it exists.document.documentElement.scrollLeft
.document.documentElement.clientLeft
if it exists.The subtraction of document.documentElement.clientLeft
/ Top
only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.
Try this:
-1 * numeric_limits<double>::max()
Reference: numeric_limits
This class is specialized for each of the fundamental types, with its members returning or set to the different values that define the properties that type has in the specific platform in which it compiles.
My issue is that I ran git diff
, then ran git reset --hard HEAD
, then realized I wanted to undo, so I tried copying the output from git diff
into a file and using git apply
, but I got an error that "patch does not apply". After switching to patch
and trying to use it, I realized that a chunk of the diff was repeated for some reason, and after removing the duplicate, patch
(and presumably also git apply
) worked.
Note that you can also combine the two, which is pretty cool (although it looks a bit odd):
// simple interpolated verbatim string
WriteLine($@"Path ""C:\Windows\{file}"" not found.");
Client send some messages need be compressed, server (kafka) decompress the string meesage
Below is my sample:
compress:
public static String compress(String str, String inEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(inEncoding));
gzip.close();
return URLEncoder.encode(out.toString("ISO-8859-1"), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
decompress:
public static String decompress(String str, String outEncoding) {
if (str == null || str.length() == 0) {
return str;
}
try {
String decode = URLDecoder.decode(str, "UTF-8");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(decode.getBytes("ISO-8859-1"));
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
return out.toString(outEncoding);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
My answer probably sucks compared to the real gurus out there, but using some simple math, string slicing, find and urllib, this little script will create a list containing link elements. I test google and my output seems right. Hope it helps!
import urllib
test = urllib.urlopen("http://www.google.com").read()
sane = 0
needlestack = []
while sane == 0:
curpos = test.find("href")
if curpos >= 0:
testlen = len(test)
test = test[curpos:testlen]
curpos = test.find('"')
testlen = len(test)
test = test[curpos+1:testlen]
curpos = test.find('"')
needle = test[0:curpos]
if needle.startswith("http" or "www"):
needlestack.append(needle)
else:
sane = 1
for item in needlestack:
print item
It's easy way to use .match()
method to string.
var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));
Wish you a nice day, sir!
A colleague had the same error and it was due to a little configuration error in IIS.
The wrong Application Pool was assigned for the web application.
Indeed we use a custom Application Pool with a specific Identity to meet our needs.
In his local IIS Manager -> Sites -> Default Web Site -> Our Web App Name -> Basic Settings... The Application Pool was "DefaultAppPool" instead of our custom Application Pool.
Setting the correct application pool solved the problem.
I had the same problem before after tried to upgrade tensorflow, I solved it by reinstalling Tensorflow and Keras.
pip uninstall tensorflow
pip uninstall keras
Then:
pip install tensorflow
pip install keras
I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.
From RFC 4918:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Array#entries
returns the index and the value, if you need both:
for (let [index, value] of array.entries()) {
}
127 means command not found
In your case, curl command was not found. Therefore it means, curl was not found.
You need to install/reinstall CURL. That's all. Get latest version for your OS from http://curl.haxx.se/download.html
Close RStudio before installation.
Try following these steps:
You can't make window.open
modal and I strongly recommend you not to go that way.
Instead you can use something like jQuery UI's dialog widget.
UPDATE:
You can use load()
method:
$("#dialog").load("resource.php").dialog({options});
This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.
And you can use an IFRAME:
$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});
This is slower, but will submit independently.
I had a similar problem and this scale worked for me like a charm:
breaks = 10**(1:10)
scale_y_log10(breaks = breaks, labels = comma(breaks))
as you want the intermediate levels, too (10^3.5), you need to tweak the formatting:
breaks = 10**(1:10 * 0.5)
m <- ggplot(diamonds, aes(y = price, x = color)) + geom_boxplot()
m + scale_y_log10(breaks = breaks, labels = comma(breaks, digits = 1))
After executing::
Answering old thread here (and a bit off-topic) because it's what I found when I was searching how to install Image Magick on Mac OS to run on the local webserver. It's not enough to brew install Imagemagick. You have to also PECL install it so the PHP module is loaded.
From this SO answer:
brew install php
brew install imagemagick
brew install pkg-config
pecl install imagick
And you may need to sudo apachectl restart
. Then check your phpinfo()
within a simple php script running on your web server.
If it's still not there, you probably have an issue with running multiple versions of PHP on the same Mac (one through the command line, one through your web server). It's beyond the scope of this answer to resolve that issue, but there are some good options out there.
You can install boost on ubuntu by using the following commands:
sudo apt update
sudo apt install libboost-all-dev
check your xml file
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" >
**<requestFocus />**
</EditText>
//Remove **<requestFocus />** from xml
You do want to add App.config to your tests class library, if you're using a tracer/logger. Otherwise nothing gets logged when you run the test through a test runner such as TestDriven.Net.
For example, I use TraceSource
in my programs, but running tests doesn't log anything unless I add an App.config file with the trace/log configuration to the test class library too.
Otherwise, adding App.config to a class library doesn't do anything.
For this particular problem, why not store up your various results in variables and then when the last of your thread is processed you can print in whatever format you want. This is especially useful if you are gonna be using your work history in other projects.
You cannot use height: 0
and height: auto
to transition the height. auto
is always relative and cannot be transitioned towards. You could however use max-height: 0
and transition that to max-height: 9999px
for example.
Sorry I couldn't comment, my rep isn't high enough...
as.character()
would be the general way rather than use paste()
for its side effect
> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"
(I presume this is a simple example and something like this:
v <- "20081101"
isn't possible?)
object-fit: cover
will do exactly what you need.
But it might not work on IE/Edge. Follow as shown below to fix it with just CSS to work on all browsers.
The approach I took was to position the image inside the container with absolute and then place it right at the centre using the combination:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
Once it is in the centre, I give to the image,
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
This makes the image get the effect of Object-fit:cover.
https://jsfiddle.net/furqan_694/s3xLe1gp/
This logic works in all browsers.
They Say that the latest rev of Tomcat (6.0.28 or 6.0.29) handles the task of redeploying servlets much better.
UIImage *image = [UIImage imageNamed:@"decline_clicked.png"];
NSData *imageData = UIImageJPEGRepresentation(image,1);
NSString *queryStringss = [NSString stringWithFormat:@"http://119.9.77.121/lets_chat/index.php/webservices/uploadfile/"];
queryStringss = [queryStringss stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[manager POST:queryStringss parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
[formData appendPartWithFileData:imageData name:@"fileName" fileName:@"decline_clicked.png" mimeType:@"image/jpeg"];
}
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *dict = [responseObject objectForKey:@"Result"];
NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[MBProgressHUD hideAllHUDsForView:self.view animated:YES];
NSLog(@"Error: %@ ***** %@", operation.responseString, error);
}];
explode('.', $string)
If you know your string has a fixed number of components you could use something like
list($a, $b) = explode('.', 'object.attribute');
echo $a;
echo $b;
Prints:
object
attribute
Along the same lines as SCFrench's answer, but with a more C# style spin..
I would (and often do) make a class containing multiple static methods. For example:
classdef Statistics
methods(Static)
function val = MyMean(data)
val = mean(data);
end
function val = MyStd(data)
val = std(data);
end
end
end
As the methods are static you don't need to instansiate the class. You call the functions as follows:
data = 1:10;
mean = Statistics.MyMean(data);
std = Statistics.MyStd(data);
Simplest way to set image as JPanel background
Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.
See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:
I guess this can be due to many things. In my case it was having "WHERE id IN" condition in my query and I was setting IDs separated by dash as a string using setString method on PreparedStatement.
Not sure if there is better way to do this but I just added placeholder in my statement and replaced it by values on my own.
If you don't need in a complete reference to the most part of algorithms and data structures that are in use and just want to get acquainted with common techniques I would recommend something more lightweight than Cormen, Sedgewick or Knuth. I think, Algorithms and Data Structures by N. Wirth is not as bad choice even in spite of it was printed far ago.
Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.
I am on Mac OSX, so I can't answer for windows users:
I added a custom keymap entry and set it to Ctrl+? + Ctrl+?, while the original default is Ctrl+- and Ctrl+Shift+- (which translates to Ctrl+ß and Ctrl+Shift+ß on my german keyboard).
One can simply modify it in the user keymap settings:
{ "key": "ctrl+left", "command": "workbench.action.navigateBack" },
{ "key": "ctrl+right", "command": "workbench.action.navigateForward" }
For the accepted answer I actually wonder :) Alt+? / Alt+? jumps wordwise for me (which is kinda standard in all editors). Did they really do this mapping for the windows version?
In order to download that driver you must have a license to SPSS. For those who do not, there is an open source tool that is very much like SPSS and will allow you to import SAV files and export them to CSV.
Here's the software
And here are the steps to export the data.
Assuming that ID
is an identity column:
INSERT INTO TheTable(HospitalID, Email, Description)
SELECT 32, Email, Description FROM TheTable
WHERE HospitalID <> 32
Try to avoid loops with SQL. Try to think in terms of sets instead.
Jasypt provides the org.jasypt.properties.EncryptableProperties class for loading, managing and transparently decrypting encrypted values in .properties files, allowing the mix of both encrypted and not-encrypted values in the same file.
http://www.jasypt.org/encrypting-configuration.html
By using an org.jasypt.properties.EncryptableProperties object, an application would be able to correctly read and use a .properties file like this:
datasource.driver=com.mysql.jdbc.Driver
datasource.url=jdbc:mysql://localhost/reportsdb
datasource.username=reportsUser
datasource.password=ENC(G6N718UuyPE5bHyWKyuLQSm02auQPUtm)
Note that the database password is encrypted (in fact, any other property could also be encrypted, be it related with database configuration or not).
How do we read this value? like this:
/*
* First, create (or ask some other component for) the adequate encryptor for
* decrypting the values in our .properties file.
*/
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("jasypt"); // could be got from web, env variable...
/*
* Create our EncryptableProperties object and load it the usual way.
*/
Properties props = new EncryptableProperties(encryptor);
props.load(new FileInputStream("/path/to/my/configuration.properties"));
/*
* To get a non-encrypted value, we just get it with getProperty...
*/
String datasourceUsername = props.getProperty("datasource.username");
/*
* ...and to get an encrypted value, we do exactly the same. Decryption will
* be transparently performed behind the scenes.
*/
String datasourcePassword = props.getProperty("datasource.password");
// From now on, datasourcePassword equals "reports_passwd"...
A very belated answer, but I created a Windows Batch file called pythonbat.bat
containing the following:
python.exe %1
@echo off
echo.
pause
and then specified pythonbat.bat
as the default handler for .py
files.
Now, when I double-click a .py
file in File Explorer, it opens a new console window, runs the Python script and then pauses (remains open), until I press any key...
No changes required to any Python scripts.
I can still open a console window and specify python myscript.py
if I want to...
(I just noticed @maurizio already posted this exact answer)
You can use Gson for this.
GSON
is a Java library that can be used to convert Java Objects into their JSON
representation. It can also be used to convert a JSON
string to an equivalent Java object.
Take a look of this Converting JSON to Java
The site at http://www.HTML-5.com/index.html does have the X-UA-Compatible meta tag but still goes into Compatibility View as indicated by the "torn page" icon in the address bar. How do you get the menu option to force IE 9 (Final Version 9.0.8112.16421) to render a page in Standards Mode? I tried right clicking that torn page icon as well as the "Alt" key trick to display the additional menu options mentioned by Rene Geuze, but those didn't work.
How about this
$.validate.addMethod(cb_selectone,
function(value,element){
if(element.length>0){
for(var i=0;i<element.length;i++){
if($(element[i]).val('checked')) return true;
}
return false;
}
return false;
},
'Please select a least one')
Now you ca do
$.validate({rules:{checklist:"cb_selectone"}});
You can even go further a specify the minimum number to select with a third param in the callback function.I have not tested it yet so tell me if it works.
You should do it in the xaml code:
<DataGrid ItemsSource="{Binding list}" [...]>
[...]
</DataGrid>
I would advise you to use an ObservableCollection
as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged
.
After struggling with this for a few days, it turns out that you can't do a window.location.reload() after a window.history.go(-2)
, because the code stops running after the window.history.go(-2)
. Also the html spec basically views a history.go(-2)
to the the same as hitting the back button and should retrieve the page as it was instead of as it now may be. There was some talk of setting caching headers in the webserver to turn off caching but I did not want to do this.
The solution for me was to use session storage to set a flag in the browser with sessionStorage.setItem('refresh', 'true');
Then in the "theme" or the next page that needs to be refreshed do:
if (sessionStorage.getItem("refresh") == "true") {
sessionStorage.removeItem("refresh"); window.location.reload()
}
So basically tell it to reload in the sessionStorage then check for that at the top of the page that needs to be reloaded.
Hope this helps someone with this bit of frustration.
The best answer I got was exporting your key, instead of just trying to import the cert file.
When you export the key from the keychain that generated the request, you get a Certificates.p12 file, which rolls the keys you need together.
Then import this into the new computer.
With keys like this, it's probably good to keep a rolled, certificate package file, because many times the "public" key, or cert file, is not enough to restore things from.
Trying to do things as smooth as possible - I here suggest modifying GuyWhoLikesPowershell's suggestion slightly.
I replaced the if and until with one while - and I check for "Stopped", since I don't want to start if status is "starting" or " Stopping".
$Service = 'ServiceName'
while ((Get-Service $Service).Status -eq 'Stopped')
{
Start-Service $Service -ErrorAction SilentlyContinue
Start-Sleep 10
}
Return "$($Service) has STARTED"
Vue.js uses vue-loader
, a loader for WebPack which is set up to rewrite/convert paths at compile time, in order to allow you to not worry about static paths that would differ between deployments (local, dev, one hosting platform or the other), by allowing you to use relative local filesystem paths. It also adds other benefits like asset caching and versioning (you can probably see this by checking the actual src
URL being generated).
So having a src that would normally be handled by vue-loader
/WebPack set to a dynamic expression, evaluated at runtime, will circumvent this mechanism and the dynamic URL generated will be invalid in the context of the actual deployment (unless it's fully qualified, that's an exception).
If instead, you would use a require
function call in the dynamic expression, vue-loader
/WebPack will see it and apply the usual magic.
For example, this wouldn't work:
<img alt="Logo" :src="logo" />
computed: {
logo() {
return this.colorMode === 'dark'
? './assets/logo-dark.png'
: './assets/logo-white.png';
}
}
While this would work:
<img alt="Logo" :src="logo" />
computed: {
logo() {
return this.colorMode === 'dark'
? require('./assets/logo-dark.png')
: require('./assets/logo-white.png');
}
}
I just found out about this myself. Took me an hour but... you live, you learn, right?
If you have global environment variables defined outside Gradle,
test {
environment "ENV_VAR", System.getenv('ENV_VAR')
useJUnitPlatform()
}
The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.
Task.Factory.StartNew(x=>
throw new Exception("I didn't account for this");
)
However, if we do this, at least the application does not crash.
Task.Factory.StartNew(x=>
try {
throw new Exception("I didn't account for this");
}
catch(Exception ex) {
//Log ex
}
)
The error you quote has nothing to do with pg_hba.conf
; it's failing to connect, not failing to authorize the connection.
Do what the error message says:
Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
You haven't shown the command that produces the error. Assuming you're connecting on localhost
port 5432
(the defaults for a standard PostgreSQL install), then either:
PostgreSQL isn't running
PostgreSQL isn't listening for TCP/IP connections (listen_addresses
in postgresql.conf
)
PostgreSQL is only listening on IPv4 (0.0.0.0
or 127.0.0.1
) and you're connecting on IPv6 (::1
) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.
PostgreSQL is listening on a different port to the one you're connecting on
(unlikely) there's an iptables
rule blocking loopback connections
(If you are not connecting on localhost
, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).
So ... check those:
ps -f -u postgres
should list postgres
processes
sudo lsof -n -u postgres |grep LISTEN
or sudo netstat -ltnp | grep postgres
should show the TCP/IP addresses and ports PostgreSQL is listening on
BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:
$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
Is the server running on host "localhost" (::1) and accepting
TCP/IP connections on port 12345?
Integer division truncates, so (50/100)
results in 0. You can cast to float
(better double
) or multiply with 100.0
(for double
precision, 100.0f
for float
precision) first,
double percentage;
// ...
percentage = 100.0*number/total;
// percentage = (double)number/total * 100;
or
float percentage;
// ...
percentage = (float)number/total * 100;
// percentage = 100.0f*number/total;
Since floating point arithmetic is not associative, the results of 100.0*number/total
and (double)number/total * 100
may be slightly different (the same holds for float
), but it's extremely unlikely to influence the first two places after the decimal point, so it probably doesn't matter which way you choose.
"SELECT Applicant.applicantId, Applicant.lastName, Applicant.firstName, Applicant.middleName, Applicant.status,Applicant.companyId, Company.name, Applicant.createDate FROM (Applicant INNER JOIN Company ON Applicant.companyId = Company.companyId) WHERE Applicant.createDate between '" +dateTimePicker1.Text.ToString() + "'and '"+dateTimePicker2.Text.ToString() +"'";
this is what i did!!
Another option:
string s2 = String.Join("," + Environment.NewLine, s1.Split(','));
('.cat').hover(
function () {
$(this).show();
},
function () {
$(this).hide();
}
);
It's the same for the others.
For the smooth fade in you can use fadeIn
and fadeOut
Boost offers a simple set of rounding functions.
#include <boost/math/special_functions/round.hpp>
double a = boost::math::round(1.5); // Yields 2.0
int b = boost::math::iround(1.5); // Yields 2 as an integer
For more information, see the Boost documentation.
Edit: Since C++11, there are std::round
, std::lround
, and std::llround
.
You're not including the C file that contains main()
when compiling, so the linker isn't seeing it.
You need to add it:
$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp
For me the solution was to change in the conf file of mysql server the parameter bind-address="127.0.0.1" or bind-address="x.x.x.x" to bind-address="0.0.0.0". Thanks.
To address specific scenario in question:
@Test
public void Test1() {
}
@Test (dependsOnMethods={"Test1"})
public void Test2() {
}
@Test (dependsOnMethods={"Test2"})
public void Test3() {
}
Nothing about could not solve my situation. This is how I solved.
Done..
We are using Response.SetCookie()
for update the old one cookies and Response.Cookies.Add()
are use to add the new cookies. Here below code CompanyId
is update in old cookie[OldCookieName]
.
HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.
Create a model which contains your list and other things you need for the view.
For example:
public class MyModel
{
public List<string> _MyList { get; set; }
}
From the action method put your desired list to the Model, _MyList
property, like:
public ActionResult ArticleList(MyModel model)
{
model._MyList = new List<string>{"item1","item2","item3"};
return PartialView(@"~/Views/Home/MyView.cshtml", model);
}
In your view access the model as follows
@model MyModel
foreach (var item in Model)
{
<div>@item</div>
}
I think it will help for start.
None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:
Edit file phpMyAdmin.conf
sudo nano /etc/httpd/conf.d/phpMyAdmin.conf
And replace this at the top:
<Directory /usr/share/phpMyAdmin/>
AddDefaultCharset UTF-8
<IfModule mod_authz_core.c>
# Apache 2.4
<RequireAny>
#Require ip 127.0.0.1
#Require ip ::1
Require all granted
</RequireAny>
</IfModule>
<IfModule !mod_authz_core.c>
# Apache 2.2
Order Deny,Allow
Deny from All
Allow from 127.0.0.1
Allow from ::1
</IfModule>
</Directory>
Kotlin Version
Simply use ViewPropertyAnimator
like this:
iv.alpha = 0.2f
iv.animate().apply {
interpolator = LinearInterpolator()
duration = 500
alpha(1f)
startDelay = 1000
start()
}
Not exactly sure this is what you are asking but you can do something like:
new Thread() {
public void run() {
System.out.println("blah");
}
}.start();
Notice the start()
method at the end of the anonymous class. You create the thread object but you need to start it to actually get another running thread.
Better than creating an anonymous Thread
class is to create an anonymous Runnable
class:
new Thread(new Runnable() {
public void run() {
System.out.println("blah");
}
}).start();
Instead overriding the run()
method in the Thread
you inject a target Runnable
to be run by the new thread. This is a better pattern.
Answer updated for 2020:
Both <object>
and <embed>
are included in the WHAT-WG HTML Living Standard (Sept 2020).
<object>
The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a child browsing context, or as an external resource to be processed by a plugin.
<embed>
The embed element provides an integration point for an external (typically non-HTML) application or interactive content.
Are there advantages/disadvantages to using one tag vs. the other?
The opinion of Mozilla Developer Network (MDN) appears (albeit fairly subtly) to very marginally favour <object>
over <embed>
but overwhelmingly, MDN, wants to recommend that wherever you can, you avoid embedding external content entirely.
[...] you are unlikely to use these elements very much — Applets haven't been used for years, Flash is no longer very popular, due to a number of reasons (see The case against plugins, below), PDFs tend to be better linked to than embedded, and other content such as images and video have much better, easier elements to handle those. Plugins and these embedding methods are really a legacy technology, and we are mainly mentioning them in case you come across them in certain circumstances like intranets, or enterprise projects.
Once upon a time, plugins were indispensable on the Web. Remember the days when you had to install Adobe Flash Player just to watch a movie online? And then you constantly got annoying alerts about updating Flash Player and your Java Runtime Environment. Web technologies have since grown much more robust, and those days are over. For virtually all applications, it's time to stop delivering content that depends on plugins and start taking advantage of Web technologies instead.
my solution:
; (function ($) {
$.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = $.fn[ name ];
$.fn[ name ] = function( speed, easing, callback ) {
if(speed == null || typeof speed === "boolean"){
var ret=cssFn.apply( this, arguments )
$.fn.triggerVisibleEvent.apply(this,arguments)
return ret
}else{
var that=this
var new_callback=function(){
callback.call(this)
$.fn.triggerVisibleEvent.apply(that,arguments)
}
var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
return ret
}
};
});
$.fn.triggerVisibleEvent=function(){
this.each(function(){
if($(this).is(':visible')){
$(this).trigger('visible')
$(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
}
})
}
})(jQuery);
for example:
if(!$info_center.is(':visible')){
$info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
}else{
processMoreLessButton()
}
function processMoreLessButton(){
//some logic
}
I used DisplayMetrics to get the screen size and then i can assign the width/height to an element in %age
It will be like this
DisplayMetrics dmetrics = new DisplayMetrics();
int widthPixels=dmetrics.widthPixels;
int heightPixels=dmetrics.heightPixels;
//setting the height of the button
button_nextPuzzle.setMinHeight((int) ((heightPixels/3)*.30));
Worked for me very well!!!
where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS')
should work.
It might work to use JmDNS on Android: http://jmdns.sourceforge.net/
There are tons of zeroconf-enabled machines out there, so this would enable discovery with more than just Android devices.
You can use this example to handle your problem:
System.out.printf( "%-15s %15s %n", "name", "lastname");
System.out.printf( "%-15s %15s %n", "Bill", "Smith");
You can play with the "%" until you find the right alignment to satisfy your needs
This is typical programming practice for defining variables that are member variables. So when you're using them later, you don't need to see where they're defined to know their scope. This is also great if you already know the scope and you're using something like intelliSense, you can start with m_
and a list of all your member variables are shown. Part of Hungarian notation, see the part about scope in the examples here.
Perhaps NSValue, just make sure your pointers are still valid after the delay (ie. no objects allocated on stack).
Declare @variable int
Exec @variable = proc_name
I have copied the relevant code below from This page. Hope this might help you.
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with upload progress
console.log(percentComplete);
}
}, false);
//Download progress
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
console.log(percentComplete);
}
}, false);
return xhr;
},
type: 'POST',
url: "/",
data: {},
success: function(data) {
//Do something success-ish
}
});
Since December 2020 xlrd no longer supports xlsx-Files as explained in the official changelog. You can use openpyxl
instead:
pip install openpyxl
And in your python-file:
import pandas as pd
pd.read_excel('path/to/file.xlsx', engine='openpyxl')
+
characters in the path component is expected to be treated literally.To be explicit: +
is only a special character in the query component.
I just found one way using the fs library. I'm not certain if it's the cleanest though.
var http = require('http'),
fs = require('fs');
fs.readFile('./index.html', function (err, html) {
if (err) {
throw err;
}
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(8000);
});
The basic concept is just raw file reading and dumping the contents. Still open to cleaner options, though!
By default p
tags are block
elements, which means they take 100% of the parent width
.
You can change their display property with:
#container p {
display:inline-block;
}
But it puts the elements side by side.
To keep each element on its own line you can use:
#container p {
clear:both;
float:left;
}
(If you use float and need to clear after floated elements, see this link for different techniques: http://css-tricks.com/all-about-floats/)
Demo: http://jsfiddle.net/CvJ3W/5/
Edit
If you go for the solution with display:inline-block
but want to keep each item in one line, you can just add a <br>
tag after each one:
<div id="container">
<p>Sample Text 1</p><br/>
<p>Sample Text 2</p><br/>
<p>Sample Text 3</p><br/>
</div>
New demo: http://jsfiddle.net/CvJ3W/7/
You can use this code:
var vid = document.getElementById("video1");
function slowPlaySpeed() {
vid.playbackRate = 0.5;
}
function normalPlaySpeed() {
vid.playbackRate = 1;
}
function fastPlaySpeed() {
vid.playbackRate = 2;
}
I've seen this occur in our 7-8 docker production system. Another solution that worked for me in production was to run
docker-compose down
docker-compose up -d
this removes the containers and seems to make 'up' create new ones from the latest image.
This doesn't yet solve my dream of down+up per EACH changed container (serially, less down time), but it works to force 'up' to update the containers.
To exclude certain characters ( <, >, %, and $), you can make a regular expression like this:
[<>%\$]
This regular expression will match all inputs that have a blacklisted character in them. The brackets define a character class, and the \ is necessary before the dollar sign because dollar sign has a special meaning in regular expressions.
To add more characters to the black list, just insert them between the brackets; order does not matter.
According to some Java documentation for regular expressions, you could use the expression like this:
Pattern p = Pattern.compile("[<>%\$]");
Matcher m = p.matcher(unsafeInputString);
if (m.matches())
{
// Invalid input: reject it, or remove/change the offending characters.
}
else
{
// Valid input.
}
Once you define a class (MyDTOClass) indicating what you expect to receive it should be as simple as...
public ActionResult Post([FromBody]MyDTOClass inputData){
... do something with input data ...
}
Thx to Julias:
Make sure your request is sent with the http header:
Content-Type: application/json
If you highlight the method Assert.assertEquals(val1, val2)
and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.
Use this
Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setCancelable(true);
dialog.setContentView(R.layout.image_show_dialog_layout);
Just tried this:
H:>"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\sqlcmd.exe" -S ".\SQL2008" 1>
and it works.. (I have the Microsoft SQL Server\100\Tools\Binn directory in my path).
Still not sure why the SQL Server 2008 version of SQLCMD doesn't work though..
It doesn't matter if the executable has arguments or not. To run GDB on any binary with a generated core file, the syntax is below.
Syntax:
gdb <binary name> <generated core file>
Eg:
gdb l3_entity 6290-corefile
Let me take the below example for more understanding.
bash-4.1$ **gdb l3_entity 6290-corefile**
**Core was generated** by `/dir1/dir2/dir3/l3_entity **Program terminated with signal SIGABRT, Aborted.**
#0
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
(gdb)
From the above output, you can guess something about core, whether it is a NULL access, SIGABORT, etc..
These numbers #0 to #10 are the stack frames of GDB. These stack frames are not of your binary. In the above 0 - 10 frames if you suspect anything wrong select that frame
(gdb) frame 8
Now to see more details about it:
(gdb) list +
To investigate the issue further, you can print the suspected variable values here at this point in time.
(gdb) print thread_name
Apache Commons collection classes is the solution.
MultiMap multiMapDemo = new MultiValueMap();
multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");
System.out.println(multiMap.get("fruit"));
// Mango Orange Blueberry
Maven Dependency
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 --
>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
The legacy solution, before 1.6, was to use .attr
and handle the returned value as a bool
. The main problem is that the returned type of .attr
has changed to string
, and therefore the comparison with == true
is broken (see http://jsfiddle.net/2vene/1/ (and switch the jquery-version)).
With 1.6 .prop
was introduced, which returns a bool
.
Nevertheless, I suggest to use .is()
, as the returned type is intrinsically bool
, like:
$('#dropUnit').is(':disabled');
$('#dropUnit').is(':enabled');
Furthermore .is()
is much more natural (in terms of "natural language") and adds more conditions than a simple attribute-comparison (eg: .is(':last')
, .is(':visible')
, ... please see documentation on selectors).
You can use mb_chars
. This respects umlaute:
class String
# Only capitalize first letter of a string
def capitalize_first
self[0] = self[0].mb_chars.upcase
self
end
end
Example:
"ümlaute".capitalize_first
#=> "Ümlaute"
If you know you will want all the matches, you could use the re.findall
function. It will return a list of all the matches. Then you can just do len(result)
for the number of matches.
There are a few alternate ways to figure out the currently used python in Linux is:
which python
command.command -v python
commandtype python
commandSimilarly On Windows with Cygwin will also result the same.
kuvivek@HOSTNAME ~
$ which python
/usr/bin/python
kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4 /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz
kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3
kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python
kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)
If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.
>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>
If you are not sure of the actual path of the python command and is available in your system, Use the following command.
pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $
The code you have is a white with low opacity.
If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.
Here is a simple demo.
If you want it to look 'more white', make it less opaque:
background:rgba(255,255,255, 0.9);
This gives you just the helper method without the side effects of loading every ActionView::Helpers method into your model:
ActionController::Base.helpers.sanitize(str)
You use standard syntax (using this
like a method) to pick the overload, inside the class:
class Foo
{
private int id;
private string name;
public Foo() : this(0, "")
{
}
public Foo(int id, string name)
{
this.id = id;
this.name = name;
}
public Foo(int id) : this(id, "")
{
}
public Foo(string name) : this(0, name)
{
}
}
then:
Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");
Note also:
base(...)
base()
For "why?":
necessary to call a non-default base-constructor, for example:
SomeBaseType(int id) : base(id) {...}
Note that you can also use object initializers in a similar way, though (without needing to write anything):
SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
z = new SomeType { DoB = DateTime.Today };
If you're using Devise, please note that
For Rails 5,
protect_from_forgery
is no longer prepended to thebefore_action
chain, so if you have setauthenticate_user
beforeprotect_from_forgery
, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or useprotect_from_forgery prepend: true
.
Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.
In 2.3.2 the collapse
class wasn't getting replaced by the in
class. The in
class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse
class correctly is removed, and the <tr>
collapses.
Use @Chad's solution for the html, and try using these links for referencing Bootstrap:
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>
How about running the following from command line,
Devenv.exe /ResetSettings
You could also save those settings in to a file, like so,
Devenv.exe /ResetSettings "C:\My Files\MySettings.vssettings"
The /ResetSettings switch, Restores Visual Studio default settings. Optionally resets the settings to the specified .vssettings file.
you can also use use case/esac
case "$string" in
"$pattern" ) echo "found";;
esac
Based on your comment to Issun:
Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>
You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.
I did test several common objects and found that an instantiated Collection
with no items added shows <No Variables>
in the watch window. If your object is indeed a collection, you can check for the <No Variables>
condition using the .Count
property:
Sub TestObj()
Dim Obj As Object
Set Obj = New Collection
If Obj Is Nothing Then
Debug.Print "Object not instantiated"
Else
If Obj.Count = 0 Then
Debug.Print "<No Variables> (ie, no items added to the collection)"
Else
Debug.Print "Object instantiated and at least one item added"
End If
End If
End Sub
It is also worth noting that if you declare any object As New
then the Is Nothing
check becomes useless. The reason is that when you declare an object As New
then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!
Dim MyObject As New Collection
If MyObject Is Nothing Then ' <--- This check always returns False
This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
static void writeStringToFile(File file, String data)
which allows you to write text to a file in one method call:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
You might also want to consider specifying the encoding for the file as well.
Swift 3 Extension Variant that preserves existing attributes.
extension UILabel {
func setLineHeight(lineHeight: CGFloat) {
guard self.text != nil && self.attributedText != nil else { return }
var attributedString = NSMutableAttributedString()
if let attributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: attributedText)
} else if let text = self.text {
attributedString = NSMutableAttributedString(string: text)
}
let style = NSMutableParagraphStyle()
style.lineSpacing = lineHeight
style.alignment = self.textAlignment
let str = NSString(string: attributedString.string)
attributedString.addAttribute(NSParagraphStyleAttributeName,
value: style,
range: str.range(of: str as String))
self.attributedText = attributedString
}
}
You have to move the css
folder into your web
folder. It seems that your web
folder on the hard drive equals the /ServletApp
folder as seen from the www. Other content than inside your web
folder cannot be accessed from the browsers.
The url of the CSS link is then
<link rel="stylesheet" type="text/css" href="/ServletApp/css/styles.css"/>
As others have mentioned, you can set the li
to display:inline;
, or float
the li
left or right. Additionally, you can also use display:flex;
on the ul
. In the snippet below I also added justify-content:space-around
to give it more spacing.
For more information on flexbox, checkout this complete guide.
#div_top_hypers {_x000D_
background-color:#eeeeee;_x000D_
display:inline; _x000D_
}_x000D_
#ul_top_hypers {_x000D_
display: flex;_x000D_
justify-content:space-around;_x000D_
list-style-type:none;_x000D_
}
_x000D_
<div id="div_top_hypers">_x000D_
<ul id="ul_top_hypers">_x000D_
<li>‣ <a href="" class="a_top_hypers"> Inbox</a></li>_x000D_
<li>‣ <a href="" class="a_top_hypers"> Compose</a></li>_x000D_
<li>‣ <a href="" class="a_top_hypers"> Reports</a></li>_x000D_
<li>‣ <a href="" class="a_top_hypers"> Preferences</a></li>_x000D_
<li>‣ <a href="" class="a_top_hypers"> logout</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
From: Andrea Chiarelli book “Beginning React: Simplify your frontend development workflow and enhance the user experience of your applications with React” :
Every React component has a props property. The purpose of this property is to collect data input passed to the component itself. JSX attribute is attached to a React element, a property with the same name is attached to the props object. So, we can access the passed data by using the attached property. In addition, the immutability of props allows us to think of components as pure functions, which are functions that have no side effects (since they don't change their input data). We can think of data passing from one component to another as a unidirectional data flow, from the parent component toward the child components. This gives us a more controllable system.
React provides a mechanism to support the automatic rendering of a component when data changes. Such a mechanism is based on the concept of state. React state is a property that represents data that changes over time. Every component supports the state property, but it should be used carefully. Components that store data that can change over time are said to be stateful components. A stateful component stores the state in the this.state property. To inform a component that the state has changed, you must use the setState() method. State initialization is the only case where you can assign a value to the this.state property without using setState().
setState() merges new data with old data already contained in the state, and overwrites the previous state setState() triggers the execution of the render() method, so you should never call render() explicitly
$(document).ready(function() {
var CookieSet = $.cookie('cookietitle', 'yourvalue');
if (CookieSet == null) {
// Do Nothing
}
if (jQuery.cookie('cookietitle')) {
// Reactions
}
});
i think i hve some joined like this from 7 Tables
SELECT a.no_surat ,
a.nm_anggota ,
a.nrp_nip_anggota ,
a.tmpt_lahir ,
a.tgl_lahir ,
a.bln_lahir ,
a.thn_lahir ,
a.alamat ,
a.keperluan ,
a.nm_jabatan ,
b.id_polsek ,b.nm_polsek,
c.id_polres ,c.nm_polres ,
d.id_pangkat , d.nm_pangkat,
e.id_pejabat , e.nm_pejabat ,
f.id_ket , f.nm_ket,
g.id_pejabat,g.nm_pejabat
FROM tbl_skhp AS a
LEFT JOIN tbl_polsek AS b ON a.id_polsek=b.id_polsek
LEFT JOIN tbl_polres AS c ON a.id_polres=c.id_polres
LEFT JOIN tbl_pangkat AS d ON a.id_pangkat=d.id_pangkat
LEFT JOIN tbl_pejabat AS e ON a.id_pejabat=e.id_pejabat
LEFT JOIN tbl_ket AS f ON a.id_ket=f.id_ket
LEFT JOIN tbl_pejabat AS g ON a.id_pejabat=g.id_pejabat
i hope u understand.... i am just sharing worked code for me.... i am use it to fetch data to my readonly form just for priview...
In short, IoC is a much broader term that includes, but is not limited to, DI
The term Inversion of Control (IoC) originally meant any sort of programming style where an overall framework or run-time controlled the program flow
Before DI had a name, people started to refer to frameworks that manage Dependencies as Inversion of Control Containers, and soon, the meaning of IoC gradually drifted towards that particular meaning: Inversion of Control over Dependencies.
Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.
I had the same error. It turns out that the cause was that the back end method was expecting different json data. In my Ajax call i had something like this:
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"url":"test"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
Now in my WebMethod, inside my C# backend code i had declared my endpoint like this:
public static string PostAjax(AjaxSettings settings)
Where AjaxSettings was declared:
public class AjaxSettings
{
public string url { get; set; }
}
The problem then was that the mapping between my ajax call and my back-end endpoint was not the same. As soon as i changed my ajax call to the following, it all worked well!
var data ='{"url":"test"}';
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"settings":'+data+'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
I had to change the data variable inside the Ajax call in order to match the method signature exactly.
It is not true that replace() works faster than replaceAll() since both uses the same code in its implementation
Pattern.compile(regex).matcher(this).replaceAll(replacement);
Now the question is when to use replace and when to use replaceAll(). When you want to replace a substring with another substring regardless of its place of occurrence in the string use replace(). But if you have some particular preference or condition like replace only those substrings at the beginning or end of a string use replaceAll(). Here are some examples to prove my point:
String str = new String("==qwerty==").replaceAll("^==", "?"); \\str: "?qwerty=="
String str = new String("==qwerty==").replaceAll("==$", "?"); \\str: "==qwerty?"
String str = new String("===qwerty==").replaceAll("(=)+", "?"); \\str: "?qwerty?"
Select many is like cross join operation in SQL where it takes the cross product.
For example if we have
Set A={a,b,c}
Set B={x,y}
Select many can be used to get the following set
{ (x,a) , (x,b) , (x,c) , (y,a) , (y,b) , (y,c) }
Note that here we take the all the possible combinations that can be made from the elements of set A and set B.
Here is a LINQ example you can try
List<string> animals = new List<string>() { "cat", "dog", "donkey" };
List<int> number = new List<int>() { 10, 20 };
var mix = number.SelectMany(num => animals, (n, a) => new { n, a });
the mix will have following elements in flat structure like
{(10,cat), (10,dog), (10,donkey), (20,cat), (20,dog), (20,donkey)}
Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit.
I was getting this Error due to incorrect syntax using in the terminal. I was using java - version. But its actually is java -version. there is no space between - and version. you can also cross check by using java -help.
i hope this will help.
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
I would consider using droidfu's image cache. It implements both an in-memory and disk-based image cache. You also get a WebImageView that takes advantage of the ImageCache library.
Here is the full description of droidfu and WebImageView: http://brainflush.wordpress.com/2009/11/23/droid-fu-part-2-webimageview-and-webgalleryadapter/
If you make all the properties animated the same, you can set each separately which will allow you to not repeat the code.
transition: all 2s;
transition-property: color, text-shadow;
There is more about it here: CSS transition shorthand with multiple properties?
I would avoid using the property all (transition-property overwrites 'all'), since you could end up with unwanted behavior and unexpected performance hits.
For anyone coming here in 2018:
Following code from here is a useful solution. No keystores etc. Just call method SSLUtilities.trustAllHttpsCertificates() before initializing the service and port (in SOAP).
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* This class provide various static methods that relax X509 certificate and
* hostname verification while using the SSL over the HTTP protocol.
*
* @author Jiramot.info
*/
public final class SSLUtilities {
/**
* Hostname verifier for the Sun's deprecated API.
*
* @deprecated see {@link #_hostnameVerifier}.
*/
private static com.sun.net.ssl.HostnameVerifier __hostnameVerifier;
/**
* Thrust managers for the Sun's deprecated API.
*
* @deprecated see {@link #_trustManagers}.
*/
private static com.sun.net.ssl.TrustManager[] __trustManagers;
/**
* Hostname verifier.
*/
private static HostnameVerifier _hostnameVerifier;
/**
* Thrust managers.
*/
private static TrustManager[] _trustManagers;
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames. This method uses the old deprecated API from the
* com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHostnames()}.
*/
private static void __trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (__hostnameVerifier == null) {
__hostnameVerifier = new SSLUtilities._FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier
com.sun.net.ssl.HttpsURLConnection
.setDefaultHostnameVerifier(__hostnameVerifier);
} // __trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones. This method uses the
* old deprecated API from the com.sun.ssl package.
*
* @deprecated see {@link #_trustAllHttpsCertificates()}.
*/
private static void __trustAllHttpsCertificates() {
com.sun.net.ssl.SSLContext context;
// Create a trust manager that does not validate certificate chains
if (__trustManagers == null) {
__trustManagers = new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager
try {
context = com.sun.net.ssl.SSLContext.getInstance("SSL");
context.init(null, __trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // __trustAllHttpsCertificates
/**
* Return true if the protocol handler property java. protocol.handler.pkgs
* is set to the Sun's com.sun.net.ssl. internal.www.protocol deprecated
* one, false otherwise.
*
* @return true if the protocol handler property is set to the Sun's
* deprecated one, false otherwise.
*/
private static boolean isDeprecatedSSLProtocol() {
return ("com.sun.net.ssl.internal.www.protocol".equals(System
.getProperty("java.protocol.handler.pkgs")));
} // isDeprecatedSSLProtocol
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
private static void _trustAllHostnames() {
// Create a trust manager that does not validate certificate chains
if (_hostnameVerifier == null) {
_hostnameVerifier = new SSLUtilities.FakeHostnameVerifier();
} // if
// Install the all-trusting host name verifier:
HttpsURLConnection.setDefaultHostnameVerifier(_hostnameVerifier);
} // _trustAllHttpsCertificates
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
private static void _trustAllHttpsCertificates() {
SSLContext context;
// Create a trust manager that does not validate certificate chains
if (_trustManagers == null) {
_trustManagers = new TrustManager[]{new SSLUtilities.FakeX509TrustManager()};
} // if
// Install the all-trusting trust manager:
try {
context = SSLContext.getInstance("SSL");
context.init(null, _trustManagers, new SecureRandom());
} catch (GeneralSecurityException gse) {
throw new IllegalStateException(gse.getMessage());
} // catch
HttpsURLConnection.setDefaultSSLSocketFactory(context
.getSocketFactory());
} // _trustAllHttpsCertificates
/**
* Set the default Hostname Verifier to an instance of a fake class that
* trust all hostnames.
*/
public static void trustAllHostnames() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHostnames();
} else {
_trustAllHostnames();
} // else
} // trustAllHostnames
/**
* Set the default X509 Trust Manager to an instance of a fake class that
* trust all certificates, even the self-signed ones.
*/
public static void trustAllHttpsCertificates() {
// Is the deprecated protocol setted?
if (isDeprecatedSSLProtocol()) {
__trustAllHttpsCertificates();
} else {
_trustAllHttpsCertificates();
} // else
} // trustAllHttpsCertificates
/**
* This class implements a fake hostname verificator, trusting any host
* name. This class uses the old deprecated API from the com.sun. ssl
* package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeHostnameVerifier}.
*/
public static class _FakeHostnameVerifier implements
com.sun.net.ssl.HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, String session) {
return (true);
} // verify
} // _FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates. This
* class uses the old deprecated API from the com.sun.ssl package.
*
* @author Jiramot.info
*
* @deprecated see {@link SSLUtilities.FakeX509TrustManager}.
*/
public static class _FakeX509TrustManager implements
com.sun.net.ssl.X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always return true, trusting for client SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isClientTrusted(X509Certificate[] chain) {
return (true);
} // checkClientTrusted
/**
* Always return true, trusting for server SSL chain peer certificate
* chain.
*
* @param chain the peer certificate chain.
* @return the true boolean value indicating the chain is trusted.
*/
public boolean isServerTrusted(X509Certificate[] chain) {
return (true);
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // _FakeX509TrustManager
/**
* This class implements a fake hostname verificator, trusting any host
* name.
*
* @author Jiramot.info
*/
public static class FakeHostnameVerifier implements HostnameVerifier {
/**
* Always return true, indicating that the host name is an acceptable
* match with the server's authentication scheme.
*
* @param hostname the host name.
* @param session the SSL session used on the connection to host.
* @return the true boolean value indicating the host name is trusted.
*/
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return (true);
} // verify
} // FakeHostnameVerifier
/**
* This class allow any X509 certificates to be used to authenticate the
* remote side of a secure socket, including self-signed certificates.
*
* @author Jiramot.info
*/
public static class FakeX509TrustManager implements X509TrustManager {
/**
* Empty array of certificate authority certificates.
*/
private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
/**
* Always trust for client SSL chain peer certificate chain with any
* authType authentication types.
*
* @param chain the peer certificate chain.
* @param authType the authentication type based on the client
* certificate.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType) {
} // checkClientTrusted
/**
* Always trust for server SSL chain peer certificate chain with any
* authType exchange algorithm types.
*
* @param chain the peer certificate chain.
* @param authType the key exchange algorithm used.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType) {
} // checkServerTrusted
/**
* Return an empty array of certificate authority certificates which are
* trusted for authenticating peers.
*
* @return a empty array of issuer certificates.
*/
public X509Certificate[] getAcceptedIssuers() {
return (_AcceptedIssuers);
} // getAcceptedIssuers
} // FakeX509TrustManager
} // SSLUtilities
MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.
When you say "by warnings" what exactly do you mean? I've usually seen it giving a hint that you may want to use var, but nothing as harsh as a warning.
There's no performance difference with var - the code is compiled to the same IL. The potential benefit is in readability - if you've already made the type of the variable crystal clear on the RHS of the assignment (e.g. via a cast or a constructor call), where's the benefit of also having it on the LHS? It's a personal preference though.
If you don't want R# suggesting the use of var, just change the options. One thing about ReSharper: it's very configurable :)
If you are allowed to use LINQ, take a look at the following example. It creates two DataTables with integer columns, fills them with some records, join them using LINQ query and outputs them to Console.
DataTable dt1 = new DataTable();
dt1.Columns.Add("CustID", typeof(int));
dt1.Columns.Add("ColX", typeof(int));
dt1.Columns.Add("ColY", typeof(int));
DataTable dt2 = new DataTable();
dt2.Columns.Add("CustID", typeof(int));
dt2.Columns.Add("ColZ", typeof(int));
for (int i = 1; i <= 5; i++)
{
DataRow row = dt1.NewRow();
row["CustID"] = i;
row["ColX"] = 10 + i;
row["ColY"] = 20 + i;
dt1.Rows.Add(row);
row = dt2.NewRow();
row["CustID"] = i;
row["ColZ"] = 30 + i;
dt2.Rows.Add(row);
}
var results = from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable() on (int)table1["CustID"] equals (int)table2["CustID"]
select new
{
CustID = (int)table1["CustID"],
ColX = (int)table1["ColX"],
ColY = (int)table1["ColY"],
ColZ = (int)table2["ColZ"]
};
foreach (var item in results)
{
Console.WriteLine(String.Format("ID = {0}, ColX = {1}, ColY = {2}, ColZ = {3}", item.CustID, item.ColX, item.ColY, item.ColZ));
}
Console.ReadLine();
// Output:
// ID = 1, ColX = 11, ColY = 21, ColZ = 31
// ID = 2, ColX = 12, ColY = 22, ColZ = 32
// ID = 3, ColX = 13, ColY = 23, ColZ = 33
// ID = 4, ColX = 14, ColY = 24, ColZ = 34
// ID = 5, ColX = 15, ColY = 25, ColZ = 35
Sometimes the column you want to filter may appear in a different position than column index 2 or have a variable name.
In this case, you can simply refer the column name you want to filter as:
columnNameToFilter = "cell_type"
expr[expr[[columnNameToFilter]] == "hesc", ]
I wrote this method:
private string GetUrlParameter(HttpRequestBase request, string parName)
{
string result = string.Empty;
var urlParameters = HttpUtility.ParseQueryString(request.Url.Query);
if (urlParameters.AllKeys.Contains(parName))
{
result = urlParameters.Get(parName);
}
return result;
}
And I call it like this:
string fooBar = GetUrlParameter(Request, "FooBar");
if (!string.IsNullOrEmpty(fooBar))
{
}
f = 0.5
a = 0
b = 9
d = [x * f for x in range(a, b)]
would be a way to do it.
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
You can use the Session object
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}
session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')
Solution:
SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)
I think that. When guest is launching page, but Admin is not logged in we don`t show something, for example the Chat.
add_action('init', 'chat_status');
function chat_status(){
if( get_option('admin_logged') === 1) { echo "<style>.chat{display:block;}</style>";}
else { echo "<style>.chat{display:none;}</style>";}
}
add_action('wp_login', function(){
if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 1);
});
add_action('wp_logout', function(){
if( wp_get_current_user()->roles[0] == 'administrator' ) update_option('admin_logged', 0);
});
Depending on what browsers/devices you are looking to support, or what you are prepared to put up with for non-compliant browsers you may want to check out the <summary>
and <detail>
tags. They are for exactly this purpose. No css is required at all as the collapsing and showing are part of the tags definition/formatting.
I've made an example here:
<details>
<summary>This is what you want to show before expanding</summary>
<p>This is where you put the details that are shown once expanded</p>
</details>
Browser support varies. Try in webkit for best results. Other browsers may default to showing all the solutions. You can perhaps fallback to the hide/show method described above.
You can simply use:
ps -o args= -f -p ProcessPid
No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)
Base64 encoding converts three 8-bit bytes (0-255) into four 6-bit bytes (0-63 aka base64). Each of the four bytes indexes an ASCII string which represents the final output as four 8-bit ASCII characters. The indexed string is typically 'A-Za-z0-9+/' with '=' used as padding. This is why encoded data is 4/3 longer.
Base64 decoding is the inverse process. And as one would expect, the decoded data is 3/4 as long.
While base64 encoding can encode plain text, its real benefit is encoding non-printable characters which may be interpreted by transmitting systems as control characters.
I suggest the original poster render $z as bytes with each bit having meaning to the application. Rendering non-printable characters as text typically invokes Unicode which produces glyphs based on your system's localization.
Base64decode("the answer to life the universe and everything") = 00101010
You can do it with the Object "ThreadGroup" and its parameter activeCount:
Remember before you merge you need to update the tag, it's quite different from branches (git pull origin tag_name
won't update your local tags). Thus, you need the following command:
git fetch --tags origin
Then you can perform git merge tag_name
to merge the tag onto a branch.
import Tkinter as tk
def quit(root):
root.destroy()
root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()
convert to string and then use built-in functions
unsigned int i;
cout<< to_string(i).length()<<endl;
If you just want to have your header font a little bit bigger then the rest, you can use ScaleTransform. so you do not depend on the real fontsize.
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor">
<TextBlock.LayoutTransform>
<ScaleTransform ScaleX="1.1" ScaleY="1.1" />
</TextBlock.LayoutTransform>
</TextBlock>
Tested code, initially creates a single archive file, then splits it:
gzip -c file.orig > file.gz
CHUNKSIZE=1073741824
PARTCNT=$[$(stat -c%s file.gz) / $CHUNKSIZE]
# the remainder is taken care of, for example for
# 1 GiB + 1 bytes PARTCNT is 1 and seq 0 $PARTCNT covers
# all of file
for n in `seq 0 $PARTCNT`
do
dd if=file.gz of=part.$n bs=$CHUNKSIZE skip=$n count=1
done
This variant omits creating a single archive file and goes straight to creating parts:
gzip -c file.orig |
( CHUNKSIZE=1073741824;
i=0;
while true; do
i=$[i+1];
head -c "$CHUNKSIZE" > "part.$i";
[ "$CHUNKSIZE" -eq $(stat -c%s "part.$i") ] || break;
done; )
In this variant, if the archive's file size is divisible by $CHUNKSIZE
, then the last partial file will have file size 0 bytes.
Or maybe
background: transparent !important;
color: #ffffff;
To remove all array elements irrespective of any given id, use this:
collection.update(
{ },
{ $pull: { 'contact.phone': { number: '+1786543589455' } } }
);
In SQL Server 2016 SSMS expand 'DATABASNAME' > expand 'SECURITY' > expand 'SCHEMA' ; right click 'SCHEMAS' from the popup left click 'NEW SCHEMAS...' add the name on the window that opens and add an owner i.e dbo click 'OK' button
This is an older question, but if you simply want to run the simulator from the Xcode 4.5 UI, you can do: Xcode > Open Developer Tool > iOS Simulator.
You can actually a method called after()
in newer version of Chrome, Firefox and Opera. The downside of this method is that Internet Explorer doesn't support it yet.
Example:
// You could create a simple node
var node = document.createElement('p')
// And then get the node where you want to append the created node after
var existingNode = document.getElementById('id_of_the_element')
// Finally you can append the created node to the exisitingNode
existingNode.after(node)
A simple HTML Code to test that is:
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<p id='up'>Up</p>_x000D_
<p id="down">Down</p>_x000D_
<button id="switchBtn" onclick="switch_place()">Switch place</button>_x000D_
<script>_x000D_
function switch_place(){_x000D_
var downElement = document.getElementById("down")_x000D_
var upElement = document.getElementById("up")_x000D_
downElement.after(upElement);_x000D_
document.getElementById('switchBtn').innerHTML = "Switched!"_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
As expected, it moves the up element after the down element
Here is from pandas docs on advanced indexing:
The section will explain exactly what you need! Turns out df.loc
(as .ix has been deprecated -- as many have pointed out below) can be used for cool slicing/dicing of a dataframe. And. It can also be used to set things.
df.loc[selection criteria, columns I want] = value
So Bren's answer is saying 'find me all the places where df.A == 0
, select column B
and set it to np.nan
'
You could add this utility function to a utility class:
public static <K, V> Map<K, V> mapOf(Object... keyValues) {
Map<K, V> map = new HashMap<>();
for (int index = 0; index < keyValues.length / 2; index++) {
map.put((K)keyValues[index * 2], (V)keyValues[index * 2 + 1]);
}
return map;
}
Map<Integer, String> map1 = YourClass.mapOf(1, "value1", 2, "value2");
Map<String, String> map2 = YourClass.mapOf("key1", "value1", "key2", "value2");
Note: in Java 9
you can use Map.of
I had the same issue, and it was solved when I used a for
loop instead of foreach
.
// foreach (var item in itemsToBeLast)
for (int i = 0; i < itemsToBeLast.Count; i++)
{
var matchingItem = itemsToBeLast.FirstOrDefault(item => item.Detach);
if (matchingItem != null)
{
itemsToBeLast.Remove(matchingItem);
continue;
}
allItems.Add(itemsToBeLast[i]);// (attachDetachItem);
}
Empty slice and nil slice are initialized differently in Go:
var nilSlice []int
emptySlice1 := make([]int, 0)
emptySlice2 := []int{}
fmt.Println(nilSlice == nil) // true
fmt.Println(emptySlice1 == nil) // false
fmt.Println(emptySlice2 == nil) // false
As for all three slices, len and cap are 0.
This works when there is multiple parts to an extension and is both short and efficient:
function removeExt($path)
{
$basename = basename($path);
return strpos($basename, '.') === false ? $path : substr($path, 0, - strlen($basename) + strlen(explode('.', $basename)[0]));
}
echo removeExt('https://example.com/file.php');
// https://example.com/file
echo removeExt('https://example.com/file.tar.gz');
// https://example.com/file
echo removeExt('file.tar.gz');
// file
echo removeExt('file');
// file
SKU can also refer to a unique identifier or code that refers to the particular stock keeping unit. These codes are not regulated or standardized. When a company receives items from a vendor, it has a choice of maintaining the vendor's SKU or creating its own.[2] This makes them distinct from Global Trade Item Number (GTIN), which are standard, global, tracking units. Universal Product Code (UPC), International Article Number (EAN), and Australian Product Number (APN) are special cases of GTINs.
its very easy to handle this situation
You can use BETWEEN CLAUSE in combination with date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )
SELECT
sc_cust_design.design_id as id,
sc_cust_design.main_image,
FROM
sc_cust_design
WHERE
sc_cust_design.publish = 1
AND **`datein`BETWEEN date_sub( now( ) , INTERVAL 30 DAY ) AND NOW( )**
Happy Coding :)
I had this path in my machine:
C:/xampp5.0/htdocs/project-recordando-symfony/project-recordando-symfony
Then I ran composer install
or/and composer update
and it returned this error:
ErrorException ZipArchive::extractTo...
That error is because your path is too much long, I changed to:
C:/xampp5.0/htdocs/p-symfony/*
and worked!
With a comma, you can specify multiple animations each with their own properties as stated in the CriticalError answer below.
Example:
animation: rotate 1s, spin 3s;
There are two issues here:
#1
-webkit-animation:spin 2s linear infinite;
-webkit-animation:scale 4s linear infinite;
The second line replaces the first one. So, has no effect.
#2
Both keyframes applies on the same property transform
As an alternative you could to wrap the image in a <div>
and animate each one separately and at different speeds.
http://jsfiddle.net/rnrlabs/x9cu53hp/
.scaler {
position: absolute;
top: 100%;
left: 50%;
width: 120px;
height: 120px;
margin:-60px 0 0 -60px;
animation: scale 4s infinite linear;
}
.spinner {
position: relative;
top: 150px;
animation: spin 2s infinite linear;
}
@keyframes spin {
100% {
transform: rotate(180deg);
}
}
@keyframes scale {
100% {
transform: scaleX(2) scaleY(2);
}
}
_x000D_
<div class="spinner">
<img class="scaler" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
<div>
_x000D_
You can use formatDate() to format the date in services or component ts. syntax:-
formatDate(value: string | number | Date, format: string, locale: string, timezone?: string): string
import the formatDate() from common module like this,
import { formatDate } from '@angular/common';
and just use it in the class like this ,
formatDate(new Date(), 'MMMM dd yyyy', 'en');
You can also use the predefined format options provided by angular like this ,
formatDate(new Date(), 'shortDate', 'en');
You can see all other predefined format options here ,
button::-moz-focus-inner {
border: 0;
}