What is the best approach to do this JAVA?
I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:
The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.
I read about SAAJ, looks like that will be more granular level of approach?
To do what?
Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?
Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport
.
Can someone send the links for some good tutorials on these topics?
That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:
What are the options we need to use while generating the code using the WSDL2Java?
No options, use wsimport
:)
I faced the same problem and solved it by adding:
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
before openConnection method.
Here is a hint Hint for gradle users without admin rights: add this line to your jaxb-task:
System.setProperty('javax.xml.accessExternalSchema', 'all')
it will look like this:
jaxb {
System.setProperty('javax.xml.accessExternalSchema', 'all')
xsdDir = "${project.name}/xsd"
xjc {
taskClassname = "com.sun.tools.xjc.XJCTask"
args = ["-npa", "-no-header"]
}
}
I think there is a simpler way:
public async Task<string> CreateSoapEnvelope()
{
string soapString = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<HelloWorld xmlns=""http://tempuri.org/"" />
</soap:Body>
</soap:Envelope>";
HttpResponseMessage response = await PostXmlRequest("your_url_here", soapString);
string content = await response.Content.ReadAsStringAsync();
return content;
}
public static async Task<HttpResponseMessage> PostXmlRequest(string baseUrl, string xmlString)
{
using (var httpClient = new HttpClient())
{
var httpContent = new StringContent(xmlString, Encoding.UTF8, "text/xml");
httpContent.Headers.Add("SOAPAction", "http://tempuri.org/HelloWorld");
return await httpClient.PostAsync(baseUrl, httpContent);
}
}
This error is probably related to a byte order mark (BOM) prior to the actual XML content. You need to parse the returned String and discard the BOM, so SAXParser can process the document correctly.
You will find a possible solution here.
Update for Swift 3 iOS 10 Beta 4
func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
let calendar = Calendar.current
let components = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
return components.day!
}
Your looking for the onSelect event in the datepicker object:
$('.selector').datepicker({
onSelect: function(dateText, inst) { ... }
});
verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"
enter code here
print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))
After much figuring out, the following worked for me:
gradle test --tests "a.b.c.MyTestFile.mySingleTest"
"\t"
not '\t'
, php doesnt escape in single quotes
You can delete all the documents from a collection in MongoDB, you can use the following:
db.users.remove({})
Alternatively, you could use the following method as well:
db.users.deleteMany({})
Follow the following MongoDB documentation, for further details.
To remove all documents from a collection, pass an empty filter document
{}
to either thedb.collection.deleteMany()
or thedb.collection.remove()
method.
Try =Year(Now())
and format the cell as General
.
Regardless of what you're trying to do there should be no need to read to and write to a file at the same time. It would also use more memory which should always be avoided. I'd suggest reading the entire file using the .ReadAll method and then close it and do whatever you need to do with the data (assuming you read the contents into a variable) and then do a write to the same file and overwrite the file. If you're concerned with having something go wrong when over-writing the current file you could always try to write it to a different file and throw an error if that doesn't work before trying to over-write the original.
Here's the flexy way to do it. Of course, it's not supported by IE8, as the user needed 7 years ago. Depending on what you need to support, some of these can be done away with.
Still, it would be nice if there was a way to do this without an outer container, just have the text align itself within it's own self.
#header {
-webkit-box-align: end;
-webkit-align-items: flex-end;
-ms-flex-align: end;
align-items: flex-end;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
height: 150px;
}
Environment variables (that you modify using the System Properties) are only propagated to subshells when you create a new subshell.
If you had a command line prompt (DOS or cygwin) open when you changed the User env vars, then they won't show up.
You need to open a new command line prompt after you change the user settings.
The equivalent in Unix/Linux is adding a line to your .bash_rc: you need to start a new shell to get the values.
I've just wrote a tiny sample app using JQuery 1.4.1 and UI 1.8rc1. All I did was specify the constructor as:
var theDialog = $(".mydialog").dialog({
autoOpen: false,
resizable: false,
modal: true,
width:'auto'
});
I know you said that this makes it take up 100% width of the browser window but it works sweet here, tested in FF3.6, Chrome and IE8.
I'm not making AJAX calls, just manually changing the HTML of the dialog but don't think that will cause any probs. Could some other css setting be knocking this out?
The only problem with this is that it makes the width off-centre but I found this support ticket where they supply a workaround of placing the dialog('open')
statement in a setTimeout to fix the problem.
Here is the contents of my head tag:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>
<link href="jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function(){
var theDialog = $(".mydialog").dialog({
autoOpen: false,
resizable: false,
modal: true,
width: 'auto'
});
$('#one').click(function(){
theDialog.html('some random text').dialog('open');
});
$('#two').click(function(){
theDialog.html('<ul><li>Apple</li><li>Orange</li><li>Banana</li><li>Strawberry</li><li>long text string to see if width changes</li></ul>').dialog('open');
});
$('#three').click(function(){
//this is only call where off-centre is noticeable so use setTimeout
theDialog.html('<img src="./random.gif" width="500px" height="500px" />');
setTimeout(function(){ theDialog.dialog('open') }, 100);;
});
});
</script>
I downloaded the js and css for Jquery UI from http://jquery-ui.googlecode.com/files/jquery-ui-1.8rc1.zip. and the body:
<div class='mydialog'></div>
<a href='#' id='one'>test1</a>
<a href='#' id='two'>test2</a>
<a href='#' id='three'>test3</a>
In order to execute a spool file in plsql Go to File->New->command window -> paste your code-> execute. Got to the directory and u will find the file.
<input type="text" ng-model="employee.age" valid-input input-pattern="[^0-9]+" placeholder="Enter an age" />
<script>
var app = angular.module('app', []);
app.controller('dataCtrl', function($scope) {
});
app.directive('validInput', function() {
return {
require: '?ngModel',
scope: {
"inputPattern": '@'
},
link: function(scope, element, attrs, ngModelCtrl) {
var regexp = null;
if (scope.inputPattern !== undefined) {
regexp = new RegExp(scope.inputPattern, "g");
}
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (regexp) {
var clean = val.replace(regexp, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
}
else {
return val;
}
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
}}); </script>
What i use:-
function isPalindrome(arg){
for(let i=0;i<arg.length;i++){
if(arg[i]!==arg[(arg.length-1)-i])
return false;
return true;
}}
while the above answers didn't solve my problem. I finally solved it by specifically going to this link https://www.microsoft.com/net/download/visual-studio-sdks and download the required sdk for Visual Studio. It was really confusing and i don't understand why but that solved my problem
Trying from the CodeBehind:
Textbox1.Attributes.Add("autocomplete", "off");
Simple and reliable solution , just override this method :
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
View v = getCurrentFocus();
if (v != null &&
(ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) &&
v instanceof EditText &&
!v.getClass().getName().startsWith("android.webkit.")) {
int scrcoords[] = new int[2];
v.getLocationOnScreen(scrcoords);
float x = ev.getRawX() + v.getLeft() - scrcoords[0];
float y = ev.getRawY() + v.getTop() - scrcoords[1];
if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom())
hideKeyboard(this);
}
return super.dispatchTouchEvent(ev);
}
public static void hideKeyboard(Activity activity) {
if (activity != null && activity.getWindow() != null && activity.getWindow().getDecorView() != null) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
}
}
In my case I wanted to compare values in cells of column E with Cells in Column G
Highlight the selection of cells to be checked in column E.
Select Conditional Format: Highlight cell rules Select one of the choices in my case it was greater than. In the left hand field of pop up use =indirect("g"&row()) where g was the row I was comparing against.
Now the row you are formatting will highlight based on if it is greater than the selection in row G
This works for every cell in Column E compared to cell in Column G of the selection you made for column E.
If G2 is greater than E2 it formats
G3 is greater than E3 it formats etc
You will need to do an Ajax call I suspect. Here is an example of an Ajax called made by jQuery to get you started. The Code logs in a user to my system but returns a bool as to whether it was successful or not. Note the ScriptMethod and WebMethod attributes on the code behind method.
in markup:
var $Username = $("#txtUsername").val();
var $Password = $("#txtPassword").val();
//Call the approve method on the code behind
$.ajax({
type: "POST",
url: "Pages/Mobile/Login.aspx/LoginUser",
data: "{'Username':'" + $Username + "', 'Password':'" + $Password + "' }", //Pass the parameter names and values
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
error: function (jqXHR, textStatus, errorThrown) {
alert("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText) },
success: function (msg) {
if (msg.d == true) {
window.location.href = "Pages/Mobile/Basic/Index.aspx";
}
else {
//show error
alert('login failed');
}
}
});
In Code Behind:
/// <summary>
/// Logs in the user
/// </summary>
/// <param name="Username">The username</param>
/// <param name="Password">The password</param>
/// <returns>true if login successful</returns>
[WebMethod, ScriptMethod]
public static bool LoginUser( string Username, string Password )
{
try
{
StaticStore.CurrentUser = new User( Username, Password );
//check the login details were correct
if ( StaticStore.CurrentUser.IsAuthentiacted )
{
//change the status to logged in
StaticStore.CurrentUser.LoginStatus = Objects.Enums.LoginStatus.LoggedIn;
//Store the user ID in the list of active users
( HttpContext.Current.Application[ SessionKeys.ActiveUsers ] as Dictionary<string, int> )[ HttpContext.Current.Session.SessionID ] = StaticStore.CurrentUser.UserID;
return true;
}
else
{
return false;
}
}
catch ( Exception ex )
{
return false;
}
}
This should work to get a specific column out of the command output "docker images":
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu 16.04 12543ced0f6f 10 months ago 122 MB
ubuntu latest 12543ced0f6f 10 months ago 122 MB
selenium/standalone-firefox-debug 2.53.0 9f3bab6e046f 12 months ago 613 MB
selenium/node-firefox-debug 2.53.0 d82f2ab74db7 12 months ago 613 MB
docker images | awk '{print $3}'
IMAGE
12543ced0f6f
12543ced0f6f
9f3bab6e046f
d82f2ab74db7
This is going to print the third column
Try below code
I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.
Private Sub ComboBox1_Change()
On Error Resume Next
Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
On Error GoTo 0
If Ret <> "" Then MsgBox Ret
End Sub
OR
On Error Resume Next
Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
If Result = "Error 2042" Then
'nothing found
ElseIf cell <> Result Then
MsgBox cell.Value
End If
On Error GoTo 0
Put a large div inside the div, center that, and the center the image inside that div.
This centers it horizontally:
HTML:
<div class="imageContainer">
<div class="imageCenterer">
<img src="http://placekitten.com/200/200" />
</div>
</div>
CSS:
.imageContainer {
width: 100px;
height: 100px;
overflow: hidden;
position: relative;
}
.imageCenterer {
width: 1000px;
position: absolute;
left: 50%;
top: 0;
margin-left: -500px;
}
.imageCenterer img {
display: block;
margin: 0 auto;
}
Demo: http://jsfiddle.net/Guffa/L9BnL/
To center it vertically also, you can use the same for the inner div, but you would need the height of the image to place it absolutely inside it.
To clarify Alvaro's answer, you need to add the -D option to the list of command lines. I'm using PyCharm, but the concept is the same:
pycharm{64,.exe,64.exe}.vmoptions:
<code>
-server
-Xms128m
...
-Didea.max.intellisense.filesize=999999 # <--- new line
</code>
You can use anonymous types for example:
var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };
For MySQL:
SELECT *
FROM permlog
ORDER BY id DESC
LIMIT 1
You want to sort the rows from highest to lowest id
, hence the ORDER BY id DESC
. Then you just want the first one so LIMIT 1
:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement.
[...]
With one argument, the value specifies the number of rows to return from the beginning of the result set
So basically you want to convert a String into an Integer right! here is what I mostly use and that is also mentioned in official documentation..
fn main() {
let char = "23";
let char : i32 = char.trim().parse().unwrap();
println!("{}", char + 1);
}
This works for both String and &str Hope this will help too.
Are you sure your processor supports Intel Virtualization (VT-x) or AMD Virtualization (AMD-V)?
Here you can find Hardware-Assisted Virtualization Detection Tool ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0ee2a17f-8538-4619-8d1c-05d27e11adb2&displaylang=en) which will tell you if your hardware supports VT-x.
Alternatively you can find your processor here: http://ark.intel.com/Default.aspx. All AMD processors since 2006 supports Virtualization.
If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.
If your string looks like below
SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"
Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines
Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
.GroupBy(o => o.PropertyName)
.ToDictionary(g => g.Key, g => g.ToList());
The simplest concept to understand, although maybe not the best, is you have three files changed and you want to stash one file.
If you do git stash
to stash them all, git stash apply
to bring them back again and then git checkout f.c
on the file in question to effectively reset it.
When you want to unstash that file run do a git reset --hard
and then run git stash apply
again, taking advantage ofthe fact that git stash apply
doesn't clear the diff from the stash stack.
This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover
attribute just like with a
elements.
Example:
div.classname:hover
{
background-color: black;
}
This changes any div
with the class classname
to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox
Happy programming!
I was behind firewall|proxy
.
In my case with Studio, ERROR: Gradle sync failed
& Cannot find symbol
.
I have used
repositories {
jcenter(); // Points to HTTPS://jcenter.bintray.com
}
Replace it with http and maven
repositories {
maven { url "http://jcenter.bintray.com" }
}
You could write it like this:
switch (varName)
{
case "afshin":
case "saeed":
case "larry":
alert('Hey');
break;
default:
alert('Default case');
break;
}
If you need to show Form2
as a modal dialog, from within Form1
do:
var form2 = new Form2();
if (form2.ShowDialog() == DialogResult.OK)
{
// process results here
}
A modal dialog will retain focus while it is open; it will set the parent windows (Form1
) "in the background" until it is closed, which is quite a common practice for settings windows.
#include <vector>
#include <numeric>
#include <sstream>
#include <iterator>
void Trim(std::string& inputString)
{
std::istringstream stringStream(inputString);
std::vector<std::string> tokens((std::istream_iterator<std::string>(stringStream)), std::istream_iterator<std::string>());
inputString = std::accumulate(std::next(tokens.begin()), tokens.end(),
tokens[0], // start with first element
[](std::string a, std::string b) { return a + " " + b; });
}
In my case, using Windows 10 and conda 4.6.11, by running the commands
conda install nb_conda
conda install -c conda-forge nb_conda_kernels
from the terminal while having the environment active didn't do the job after I opened Jupyter from the same command line using conda jupyter notebook
.
The solution was apparently to opened Jupyter from the Anaconda Navigator by going to my environment in Environments: Open Anaconda Navigator, select the environment in Environments, press on the "play" button on the chosen environment, and select 'open with Jupyter Notebook'.
Environments in Anaconda Navigator to run Jupyter from the selected environment
Simple way without methods
int x = 1, y = 2, z = 3;
int biggest = x;
if (y > biggest) {
biggest = y;
}
if (z > biggest) {
biggest = z;
}
System.out.println(biggest);
// System.out.println(Math.max(Math.max(x,y),z));
I've been told that COALESCE is less costly than ISNULL, but research doesn't indicate that. ISNULL takes only two parameters, the field being evaluated for NULL, and the result you want if it is evaluated as NULL. COALESCE will take any number of parameters, and return the first value encountered that isn't NULL.
There's a much more thorough description of the details here http://www.mssqltips.com/sqlservertip/2689/deciding-between-coalesce-and-isnull-in-sql-server/
If you have access to the application package, then you can install with the -r option and it will kill the process if it is currently running as a side effect. Like this:
adb -d install -r MyApp.apk ; adb -d shell am start -a android.intent.action.MAIN -n com.MyCompany.MyApp/.MyActivity
The -r option preserves the data currently associated with the app. However, if you want a clean slate like you mention you might not want to use that option.
IE 8 actually uses the first button it encounters submit or button. Instead of easily indicating which is desired by making it a input type=submit the order on the page is actually significant.
This is not exactly correct idea of using Observable
In the component you have to declare class member which will hold an object (something you are going to use in your component)
export class MyComponent {
name: string = "";
}
Then a Service
will be returning you an Observable
:
getValueFromObservable():Observable<string> {
return this.store.map(res => res.json());
}
Component
should prepare itself to be able to retrieve a value from it:
OnInit(){
this.yourServiceName.getValueFromObservable()
.subscribe(res => this.name = res.name)
}
You have to assign a value from an Observable
to a variable:
And your template will be consuming variable name
:
<div> {{ name }} </div>
Another way of using Observable
is through async
pipe http://briantroncone.com/?p=623
Note: If it's not what you are asking, please update your question with more details
When the Resolve Conflicts->Content Menu are disabled, one may be on the Pending files list. We need to select the Conflicted files option from the drop down (top)
hope it helps
I want to add somethings different from definitions of words. Most of them will be visual.
Technically, LDAP is just a protocol that defines the method by which directory data is accessed.Necessarily, it also defines and describes how data is represented in the directory service
Data is represented in an LDAP system as a hierarchy of objects, each of which is called an entry. The resulting tree structure is called a Directory Information Tree (DIT). The top of the tree is commonly called the root (a.k.a base or the suffix).
To navigate the DIT we can define a path (a DN) to the place where our data is (cn=DEV-India,ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com will take us to a unique entry) or we can define a path (a DN) to where we think our data is (say, ou=Distrubition Groups,dc=gp,dc=gl,dc=google,dc=com) then search for the attribute=value or multiple attribute=value pairs to find our target entry (or entries).
If you want to get more depth information, you visit here
Here is a little research that explored RDBMS vs NoSQL using MySQL vs Mongo, the conclusions were inline with @Sean Reilly's response. In short, the benefit comes from the design, not some raw speed difference. Conclusion on page 35-36:
RDBMS vs NoSQL: Performance and Scaling Comparison
The project tested, analysed and compared the performance and scalability of the two database types. The experiments done included running different numbers and types of queries, some more complex than others, in order to analyse how the databases scaled with increased load. The most important factor in this case was the query type used as MongoDB could handle more complex queries faster due mainly to its simpler schema at the sacrifice of data duplication meaning that a NoSQL database may contain large amounts of data duplicates. Although a schema directly migrated from the RDBMS could be used this would eliminate the advantage of MongoDB’s underlying data representation of subdocuments which allowed the use of less queries towards the database as tables were combined. Despite the performance gain which MongoDB had over MySQL in these complex queries, when the benchmark modelled the MySQL query similarly to the MongoDB complex query by using nested SELECTs MySQL performed best although at higher numbers of connections the two behaved similarly. The last type of query benchmarked which was the complex query containing two JOINS and and a subquery showed the advantage MongoDB has over MySQL due to its use of subdocuments. This advantage comes at the cost of data duplication which causes an increase in the database size. If such queries are typical in an application then it is important to consider NoSQL databases as alternatives while taking in account the cost in storage and memory size resulting from the larger database size.
For example:
you can use:
df %>% filter(!is.na(a))
to remove the NA in column a.
If you're using Python 3.3 or above, I'd recommend the built-in get_terminal_size()
as already recommended. However if you are stuck with an older version and want a simple, cross-platform way of doing this, you could use asciimatics. This package supports versions of Python back to 2.7 and uses similar options to those suggested above to get the current terminal/console size.
Simply construct your Screen
class and use the dimensions
property to get the height and width. This has been proven to work on Linux, OSX and Windows.
Oh - and full disclosure here: I am the author, so please feel free to open a new issue if you have any problems getting this to work.
I also came across the same issue. I was trying to build the project with a clean install
goal. I simply changed it to clean package -o
in the run configuration. Then I re-built the project and it worked for me.
Put this in a file and make it executable:
#!/bin/bash
start=`grep -n $1 < $3 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[0]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find start pattern!" 1>&2
exit 1
fi
stop=`tail -n +$start < $3 | grep -n $2 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[1]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find end pattern!" 1>&2
exit 1
fi
stop=$(( $stop + $start - 1))
sed "$start,$stop!d" < $3
Execute the file with arguments (NOTE that the script does not handle spaces in arguments!):
To use with your example, use arguments: 1234 5555 myfile.txt
Includes lines with starting and stopping pattern.
If you are using Rails 5 and above, the following solution will work.
#delete based on id
user_id = 50
User.find(id: user_id).delete_all
#delete based on condition
threshold_age = 20
User.where(age: threshold_age).delete_all
https://www.rubydoc.info/docs/rails/ActiveRecord%2FNullRelation:delete_all
MessageBox::Show
uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
Funnily enough, adjusting the padding seems to do it.
.arrow {
border: solid rgb(2, 0, 0);
border-width: 0 3px 3px 0;
display: inline-block;
}
.first{
padding: 2vh;
}
.second{
padding: 4vh;
}
.left {
transform: rotate(135deg);
-webkit-transform: rotate(135deg);
}
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
I created this simple example from different search results on the internet.
public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
//Create base address
string baseAddress = "net.pipe://localhost/MyService";
ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));
//Net named pipe
NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);
//MEX - Meta data exchange
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");
return serviceHost;
}
Using the above URI I can add a reference in my client to the web service.
I am working with 35000 lines of data.
$f=fopen("veri1.txt","r");
$i=0;
while(!feof($f)){
$i++;
$line=mb_convert_encoding(fgets($f), 'HTML-ENTITIES', "UTF-8");
echo $line;
}
This code convert my strange characters into normal.
To highlight a block of code in Notepad++, please do the following steps
Style token
and select any of the five choices available ( styles from Using 1st style
to using 5th style
). Each is of different colors.If you want yellow color choose using 3rd style
.If you want to create your own style you can use Style Configurator
under Settings
menu.
If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.
But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.
Here is shortest way of doing it.
$userRecord = Model::where(['email'=>$email, 'password'=>$password])->first();
If speed is your primary concern, then I'd simply go with
double r = (double)rand() / (double)RAND_MAX;
You can press q to exit.
git hist
is using a pager tool so you can scroll up and down the results before returning to the console.
in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #
ONELINER:
var min= dates.sort((a,b)=>a-b)[0], max= dates.slice(-1)[0];
result in variables min
and max
, complexity O(nlogn), editable example here. If your array has no-date values (like null
) first clean it by dates=dates.filter(d=> d instanceof Date);
.
var dates = [];_x000D_
dates.push(new Date("2011-06-25")); // I change "/" to "-" in "2011/06/25"_x000D_
dates.push(new Date("2011-06-26")); // because conosle log write dates _x000D_
dates.push(new Date("2011-06-27")); // using "-"._x000D_
dates.push(new Date("2011-06-28"));_x000D_
_x000D_
var min= dates.sort((a,b)=>a-b)[0], max= dates.slice(-1)[0];_x000D_
_x000D_
console.log({min,max});
_x000D_
Better use $_SERVER['REQUEST_METHOD']
:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
Here's a pretty ggplot2 solution:
library(ggplot2)
library(scales) # makes pretty labels on the x-axis
breaks=c(0,1,2,3,4,5,25)
ggplot(mydata,aes(x = V3)) +
geom_histogram(breaks = log10(breaks)) +
scale_x_log10(
breaks = breaks,
labels = scales::trans_format("log10", scales::math_format(10^.x))
)
Note that to set the breaks in geom_histogram, they had to be transformed to work with scale_x_log10
Don't think of the colon as part of the function name, think of it as a separator, if you don't have anything to separate (no value to go with the function) then you don't need it.
I'm not sure why but all this OO stuff seems to be foreign to Apple developers. I would strongly suggest grabbing Visual Studio Express and playing around with that too. Not because one is better than the other, just it's a good way to look at the design issues and ways of thinking.
Like
introspection = reflection
+ before functions/properties = static
- = instance level
It's always good to look at a problem in different ways and programming is the ultimate puzzle.
You can use below command if you want to print entire line and file name if the occurrence of particular word in current directory you are searching.
grep -m 1 -r "Not caching" * | head -1
You can always check this maintained list to timezones
In my case, I disabled "Block TCP 445" on Windows Defender Firewall with Advanced Security and it worked. Then enabled it again after setting shared drives on Docker.
Though it's probably suggested to get some heavier validation via JS or on the server, HTML5 does support this via the pattern attribute.
<input type= "text" name= "name" pattern= "[0-9]" title= "Title"/>
Remember that a JavaScript code unit is 16 bits wide. Therefore the hex string form will be 4 digits per code unit.
usage:
var str = "\u6f22\u5b57"; // "\u6f22\u5b57" === "??"
alert(str.hexEncode().hexDecode());
String to hex form:
String.prototype.hexEncode = function(){
var hex, i;
var result = "";
for (i=0; i<this.length; i++) {
hex = this.charCodeAt(i).toString(16);
result += ("000"+hex).slice(-4);
}
return result
}
Back again:
String.prototype.hexDecode = function(){
var j;
var hexes = this.match(/.{1,4}/g) || [];
var back = "";
for(j = 0; j<hexes.length; j++) {
back += String.fromCharCode(parseInt(hexes[j], 16));
}
return back;
}
Syntax
"your image name".setColorFilter("your context".getResources().getColor("color name"));
Example
myImage.setColorFilter(mContext.getResources().getColor(R.color.deep_blue_new));
The best is by using TextView
instead.
Reading console input is hard, you need to handle special keys like Ctrl, Alt, also cursor keys and Backspace/Delete. On some keyboard layouts, like Swedish Ctrl is even needed to enter keys that exist directly on US keyboard. I believe that trying to handle this using the "low-level" Console.ReadKey(true)
is just very hard, so the easiest and most robust way is to just to disable "console input echo" during entering password using a bit of WINAPI.
The sample below is based on answer to Read a password from std::cin question.
private enum StdHandle
{
Input = -10,
Output = -11,
Error = -12,
}
private enum ConsoleMode
{
ENABLE_ECHO_INPUT = 4
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(StdHandle nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out int lpMode);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetConsoleMode(IntPtr hConsoleHandle, int dwMode);
public static string ReadPassword()
{
IntPtr stdInputHandle = GetStdHandle(StdHandle.Input);
if (stdInputHandle == IntPtr.Zero)
{
throw new InvalidOperationException("No console input");
}
int previousConsoleMode;
if (!GetConsoleMode(stdInputHandle , out previousConsoleMode))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not get console mode.");
}
// disable console input echo
if (!SetConsoleMode(stdInputHandle , previousConsoleMode & ~(int)ConsoleMode.ENABLE_ECHO_INPUT))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not disable console input echo.");
}
// just read the password using standard Console.ReadLine()
string password = Console.ReadLine();
// reset console mode to previous
if (!SetConsoleMode(stdInputHandle , previousConsoleMode))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not reset console mode.");
}
return password;
}
#pragma mark -
#pragma mark - UICollectionView Datasource and Delegates
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return Arr_AllCulturalButtler.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *coll=@"FromCulturalbutlerCollectionViewCell";
FromCulturalbutlerCollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:coll forIndexPath:indexPath];
cell.lbl_categoryname.text=[[Arr_AllCulturalButtler objectAtIndex:indexPath.row] Category_name];
cell.lbl_date.text=[[Arr_AllCulturalButtler objectAtIndex:indexPath.row] event_Start_date];
cell.lbl_location.text=[[Arr_AllCulturalButtler objectAtIndex:indexPath.row] Location_name];
[cell.Img_Event setImageWithURL:[APPDELEGATE getURLForMediumSizeImage:[(EventObj *)[Arr_AllCulturalButtler objectAtIndex:indexPath.row] Event_image_name]] placeholderImage:nil usingActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
cell.button_Bookmark.selected=[[Arr_AllCulturalButtler objectAtIndex:indexPath.row] Event_is_bookmarked];
[cell.button_Bookmark addTarget:self action:@selector(btn_bookmarkClicked:) forControlEvents:UIControlEventTouchUpInside];
cell.button_Bookmark.tag=indexPath.row;
return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:SEGUE_CULTURALBUTLER_KULTURELLIS_DETAIL sender:self];
}
// stroy board navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"Overview_Register"])
{
WDRegisterViewController *obj=(WDRegisterViewController *)[segue destinationViewController];
obj.str_Title=@"Edit Profile";
obj.isRegister=NO;
}
}
[self performSegueWithIdentifier:@"Overview_Measure" sender:nil];
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
WDPeekViewController *Peek = (WDPeekViewController *)[sb instantiateViewControllerWithIdentifier:@"WDPeekViewController"];
[self.navigationController pushViewController:tabBarController animated:YES];
I was running into the exact same problem that Saurav described, but I really needed to find a solution that did not require anything other than Route 53 and S3. I created a how-to guide for my blog detailing what I did.
Here is what I came up with.
Using only the tools available in Amazon S3 and Amazon Route 53, create a URL Redirect that automatically forwards http://url-redirect-example.vivekmchawla.com to the AWS Console sign-in page aliased to "MyAccount", located at https://myaccount.signin.aws.amazon.com/console/ .
This guide will teach you set up URL forwarding to any URL, not just ones from Amazon. You will learn how to set up forwarding to specific folders (like "/console" in my example), and how to change the protocol of the redirect from HTTP to HTTPS (or vice versa).
Open the S3 management console and click "Create Bucket".
Choose a Bucket Name. This step is really important! You must name the bucket EXACTLY the same as the URL you want to set up for forwarding. For this guide, I'll use the name "url-redirect-example.vivekmchawla.com".
Select whatever region works best for you. If you don't know, keep the default.
Don't worry about setting up logging. Just click the "Create" button when you're ready.
Paste the following XML snippet in it's entirety.
<RoutingRules>
<RoutingRule>
<Redirect>
<Protocol>https</Protocol>
<HostName>myaccount.signin.aws.amazon.com</HostName>
<ReplaceKeyPrefixWith>console/</ReplaceKeyPrefixWith>
<HttpRedirectCode>301</HttpRedirectCode>
</Redirect>
</RoutingRule>
</RoutingRules>
If you're curious about what the above XML is doing, visit the AWM Documentation for "Syntax for Specifying Routing Rules". A bonus technique (not covered here) is forwarding to specific pages at the destination host, for example http://redirect-destination.com/console/special-page.html
. Read about the <ReplaceKeyWith>
element if you need this functionality.
Make note of the Static Website Hosting "endpoint" that Amazon automatically created for this bucket. You'll need this for later, so highlight the entire URL, then copy and paste it to notepad.
CAUTION! At this point you can actually click this link to check to see if your Redirection Rules were entered correctly, but be careful! Here's why...
Let's say you entered the wrong value inside the <Hostname>
tags in your Redirection Rules. Maybe you accidentally typed myaccount.amazon.com
, instead of myaccount.signin.aws.amazon.com
. If you click the link to test the Endpoint URL, AWS will happily redirect your browser to the wrong address!
After noticing your mistake, you will probably edit the <Hostname>
in your Redirection Rules to fix the error. Unfortunately, when you try to click the link again, you'll most likely end up being redirected back to the wrong address! Even though you fixed the <Hostname>
entry, your browser is caching the previous (incorrect!) entry. This happens because we're using an HTTP 301 (permanent) redirect, which browsers like Chrome and Firefox will cache by default.
If you copy and paste the Endpoint URL to a different browser (or clear the cache in your current one), you'll get another chance to see if your updated <Hostname>
entry is finally the correct one.
To be safe, if you want to test your Endpoint URL and Redirect Rules, you should open a private browsing session, like "Incognito Mode" in Chrome. Copy, paste, and test the Endpoint URL in Incognito Mode and anything cached will go away once you close the session.
Clicking "Create Record Set" will open up the Create Record Set window on the right side of the Route53 Management Console.
In the Name field, enter the hostname portion of the URL that you used when naming your S3 bucket. The "hostname portion" of the URL is everything to the LEFT of your Hosted Zone's name. I named my S3 bucket "url-redirect-example.vivekmchawla.com", and my Hosted Zone is "vivekmchawla.com", so the hostname portion I need to enter is "url-redirect-example".
Select "CNAME - Canonical name" for the Type of this Record Set.
For the Value, paste in the Endpoint URL of the S3 bucket we created back in Step 3.
Click the "Create Record Set" button. Assuming there are no errors, you'll now be able to see a new CNAME record in your Hosted Zone's list of Record Sets.
Open up a new browser tab and type in the URL that we just set up. For me, that's http://url-redirect-example.vivekmchawla.com. If everything worked right, you should be sent directly to an AWS sign-in page.
Because we used the myaccount.signin.aws.amazon.com
alias as our redirect's destination URL, Amazon knows exactly which account we're trying to access, and takes us directly there. This can be very handy if you want to give a short, clean, branded AWS login link to employees or contractors.
I personally love the various AWS services, but if you've decided to migrate DNS management to Amazon Route 53, the lack of easy URL forwarding can be frustrating. I hope this guide helped make setting up URL forwarding for your Hosted Zones a bit easier.
If you'd like to learn more, please take a look at the following pages from the AWS Documentation site.
Cheers!
1.Monolithic Kernel (Pure Monolithic) :all
All Kernel Services From single component
(-) addition/removal is not possible, less/Zero flexible
(+) inter Component Communication is better
e.g. :- Traditional Unix
2.Micro Kernel :few
few services(Memory management ,CPU management,IPC etc) from core kernel, other services(File management,I/O management. etc.) from different layers/component
Split Approach [Some services is in privileged(kernel) mode and some are in Normal(user) mode]
(+)flexible for changes/up-gradations
(-)communication overhead
e.g.:- QNX etc.
3.Modular kernel(Modular Monolithic) :most
Combination of Micro and Monolithic kernel
Collection of Modules -- modules can be --> Static + Dynamic
Drivers come in the form of Modules
e.g. :- Linux Modern OS
SELECT to_char(emp_login_date,'DD-MON-YYYY HH24:MI:SS'),A.*
FROM emp_log A
WHERE emp_login_date BETWEEN to_date(to_char('21-MAY-2015 11:50:14'),'DD-MON-YYYY HH24:MI:SS')
AND
to_date(to_char('22-MAY-2015 17:56:52'),'DD-MON-YYYY HH24:MI:SS')
ORDER BY emp_login_date
A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:
So we need three divs:
First let us define the CSS:
#hider
{
position:absolute;
top: 0%;
left: 0%;
width:1600px;
height:2000px;
margin-top: -800px; /*set to a negative number 1/2 of your height*/
margin-left: -500px; /*set to a negative number 1/2 of your width*/
/*
z- index must be lower than pop up box
*/
z-index: 99;
background-color:Black;
//for transparency
opacity:0.6;
}
#popup_box
{
position:absolute;
top: 50%;
left: 50%;
width:10em;
height:10em;
margin-top: -5em; /*set to a negative number 1/2 of your height*/
margin-left: -5em; /*set to a negative number 1/2 of your width*/
border: 1px solid #ccc;
border: 2px solid black;
z-index:100;
}
It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
Here comes the java Script:
$(document).ready(function () {
//hide hider and popup_box
$("#hider").hide();
$("#popup_box").hide();
//on click show the hider div and the message
$("#showpopup").click(function () {
$("#hider").fadeIn("slow");
$('#popup_box').fadeIn("slow");
});
//on click hide the message and the
$("#buttonClose").click(function () {
$("#hider").fadeOut("slow");
$('#popup_box').fadeOut("slow");
});
});
And finally the HTML:
<div id="hider"></div>
<div id="popup_box">
Message<br />
<a id="buttonClose">Close</a>
</div>
<div id="content">
Page's main content.<br />
<a id="showpopup">ClickMe</a>
</div>
I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.
This.
$.each(
$('#some-element'),
function(i, item){
item.addEventListener('DOMNodeRemovedFromDocument',
function(e){ console.log('I has been removed'); console.log(e);
})
})
And another expansion:
# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)
If you want to assign new column names you can do following on data.frame
:
# an identical effect can be achieved with colnames()
names(d) <- LETTERS[1:5]
> d
A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3
If you, however run previous command on matrix
, you'll mess things up:
names(m) <- LETTERS[1:5]
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 3 2 4 3 4
[2,] 2 2 3 1 3
[3,] 3 2 1 2 4
[4,] 4 3 3 3 2
[5,] 1 3 2 4 3
attr(,"names")
[1] "A" "B" "C" "D" "E" NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[20] NA NA NA NA NA NA
Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames()
.
So there...
You should use profiles.
<profiles>
<profile>
<id>otherOutputDir</id>
<build>
<directory>yourDirectory</directory>
</build>
</profile>
</profiles>
And start maven with your profile
mvn compile -PotherOutputDir
If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :
<properties>
<buildDirectory>${project.basedir}/target</buildDirectory>
</properties>
<build>
<directory>${buildDirectory}</directory>
</build>
And compile like this :
mvn compile -DbuildDirectory=test
That's because you can't change the target directory by using -Dproject.build.directory
You can try using fast-export:
cd ~
git clone https://github.com/frej/fast-export.git
git init git_repo
cd git_repo
~/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
git checkout HEAD
Also have a look at this SO question.
If you're using Mercurial version below 4.6, adrihanu got your back:
As he stated in his comment: "In case you use Mercurial < 4.6 and you got "revsymbol not found" error. You need to update your Mercurial or downgrade fast-export by running git checkout tags/v180317 inside ~/fast-export directory.".
To answer the original question, the best way IMO is just redirecting subprocess stdout
directly to your program's stdout
(optionally, the same can be done for stderr
, as in example below)
p = Popen(cmd, stdout=sys.stdout, stderr=sys.stderr)
p.communicate()
It should be:
SELECT SalesID, COUNT(*)
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1
Regarding your initial query:
Edit:
And I just thought of this, if you want to see WHICH items are in there more than once (but this depends on which database you are using):
;WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY SalesID ORDER BY SalesID) AS [Num]
FROM AXDelNotesNoTracking
)
SELECT *
FROM cte
WHERE cte.Num > 1
Of course, this just shows the rows that have appeared with the same SalesID but does not show the initial SalesID value that has appeared more than once. Meaning, if a SalesID shows up 3 times, this query will show instances 2 and 3 but not the first instance. Still, it might help depending on why you are looking for multiple SalesID values.
Edit2:
The following query was posted by APC below and is better than the CTE I mention above in that it shows all rows in which a SalesID has appeared more than once. I am including it here for completeness. I merely added an ORDER BY to keep the SalesID values grouped together. The ORDER BY might also help in the CTE above.
SELECT *
FROM AXDelNotesNoTracking
WHERE SalesID IN
( SELECT SalesID
FROM AXDelNotesNoTracking
GROUP BY SalesID
HAVING COUNT(*) > 1
)
ORDER BY SalesID
Here's how I do it
var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 60)
{
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 60 * 2)
{
return "a minute ago";
}
if (delta < 45 * 60)
{
return ts.Minutes + " minutes ago";
}
if (delta < 90 * 60)
{
return "an hour ago";
}
if (delta < 24 * 60 * 60)
{
return ts.Hours + " hours ago";
}
if (delta < 48 * 60 * 60)
{
return "yesterday";
}
if (delta < 30 * 24 * 60 * 60)
{
return ts.Days + " days ago";
}
if (delta < 12 * 30 * 24 * 60 * 60)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
Suggestions? Comments? Ways to improve this algorithm?
I think Semaphore is what you are looking for, it will block the main process after counting down to 0. Sample code:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# simulate a time-consuming task by sleeping
time.sleep(5)
# `release` will add 1 to `sema`, allowing other
# processes blocked on it to continue
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
# once 20 processes are running, the following `acquire` call
# will block the main process since `sema` has been reduced
# to 0. This loop will continue only after one or more
# previously created processes complete.
sema.acquire()
p = Process(target=f, args=(i, sema))
all_processes.append(p)
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The following code is more structured since it acquires and releases sema
in the same function. However, it will consume too much resources if total_task_num
is very large:
from multiprocessing import Process
from multiprocessing import Semaphore
import time
def f(name, sema):
print('process {} starting doing business'.format(name))
# `sema` is acquired and released in the same
# block of code here, making code more readable,
# but may lead to problem.
sema.acquire()
time.sleep(5)
sema.release()
if __name__ == '__main__':
concurrency = 20
total_task_num = 1000
sema = Semaphore(concurrency)
all_processes = []
for i in range(total_task_num):
p = Process(target=f, args=(i, sema))
all_processes.append(p)
# the following line won't block after 20 processes
# have been created and running, instead it will carry
# on until all 1000 processes are created.
p.start()
# inside main process, wait for all processes to finish
for p in all_processes:
p.join()
The above code will create total_task_num
processes but only concurrency
processes will be running while other processes are blocked, consuming precious system resources.
You're just trying to concatenate the two byte
arrays?
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];
for (int i = 0; i < combined.length; ++i)
{
combined[i] = i < one.length ? one[i] : two[i - one.length];
}
Or you could use System.arraycopy
:
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];
System.arraycopy(one,0,combined,0 ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);
Or you could just use a List
to do the work:
byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));
byte[] combined = list.toArray(new byte[list.size()]);
Or you could simply use ByteBuffer
with the advantage of adding many arrays.
byte[] allByteArray = new byte[one.length + two.length + three.length];
ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);
byte[] combined = buff.array();
I have found a solution for anyone in this problem change the socket dir to a new location in my.cnf file
socket=/var/lib/mysql/mysql2.sock
and service mysqld start
or the fast way as GeckoSEO answered
# mv /var/lib/mysql/mysql.sock /var/lib/mysql/mysql.sock.bak
# service mysqld start
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.
How serialization works
This illustration shows the overall process of serialization:
The object is serialized to a stream that carries the data. The stream may also have information about the object's type, such as its version, culture, and assembly name. From that stream, the object can be stored in a database, a file, or memory.
Details in Microsoft Docs.
Splendid answer from Ben. However I'm surprised that the Affinity Propagation (AP) method has been here suggested just to find the number of cluster for the k-means method, where in general AP do a better job clustering the data. Please see the scientific paper supporting this method in Science here:
Frey, Brendan J., and Delbert Dueck. "Clustering by passing messages between data points." science 315.5814 (2007): 972-976.
So if you are not biased toward k-means I suggest to use AP directly, which will cluster the data without requiring knowing the number of clusters:
library(apcluster)
apclus = apcluster(negDistMat(r=2), data)
show(apclus)
If negative euclidean distances are not appropriate, then you can use another similarity measures provided in the same package. For example, for similarities based on Spearman correlations, this is what you need:
sim = corSimMat(data, method="spearman")
apclus = apcluster(s=sim)
Please note that those functions for similarities in the AP package are just provided for simplicity. In fact, apcluster() function in R will accept any matrix of correlations. The same before with corSimMat() can be done with this:
sim = cor(data, method="spearman")
or
sim = cor(t(data), method="spearman")
depending on what you want to cluster on your matrix (rows or cols).
$hours = floor($seconds / 3600);
$mins = floor($seconds / 60 % 60);
$secs = floor($seconds % 60);
If you want to get time format:
$timeFormat = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);
__dirname will give you the root directory, as long as you're in a file that's in the root directory.
// ProjectDirectory.js (this file is in the project's root directory because you are putting it there).
module.exports = {
root() {
return __dirname;
}
}
In some other file:
const ProjectDirectory = require('path/to/ProjectDirectory');
console.log(`Project root directory is ${ProjectDirectory.root}`);
Path to the current .exe
#include <Windows.h>
std::wstring getexepathW()
{
wchar_t result[MAX_PATH];
return std::wstring(result, GetModuleFileNameW(NULL, result, MAX_PATH));
}
std::wcout << getexepathW() << std::endl;
// -------- OR --------
std::string getexepathA()
{
char result[MAX_PATH];
return std::string(result, GetModuleFileNameA(NULL, result, MAX_PATH));
}
std::cout << getexepathA() << std::endl;
I found out that the image that you are specify with the og:image, has to actually be present in the HTML page inside an image tag.
the thumbnail appeared for me only after i added an image tag for the image. it was commented out. but worked.
It could be that your code is compiled with x64 therefore have to enable the Default Processor Architecture as X64.
Test > Test Settings > Default Processor Architecture > X64
For those like me who wonder how legacy apps are treated, I did a bit of testing and computation on the subject.
Thanks to @hannes-sverrisson hint, I started on the assumption that a legacy app is treated with a 320x568 view in iPhone 6 and iPhone 6 plus.
The test was made with a simple black background [email protected]
with a white border. The background has a size of 640x1136 pixels, and it is black with an inner white border of 1 pixel.
Below are the screenshots provided by the simulator:
On the iPhone 6 screenshot, we can see a 1 pixel margin on top and bottom of the white border, and a 2 pixel margin on the iPhone 6 plus screenshot. This gives us a used space of 1242x2204 on iPhone 6 plus, instead of 1242x2208, and 750x1332 on the iPhone 6, instead of 750x1334.
We can assume that those dead pixels are meant to respect the iPhone 5 aspect ratio:
iPhone 5 640 / 1136 = 0.5634
iPhone 6 (used) 750 / 1332 = 0.5631
iPhone 6 (real) 750 / 1334 = 0.5622
iPhone 6 plus (used) 1242 / 2204 = 0.5635
iPhone 6 plus (real) 1242 / 2208 = 0.5625
Second, it is important to know that @2x resources will be scaled not only on iPhone 6 plus (which expects @3x assets), but also on iPhone 6. This is probably because not scaling the resources would have led to unexpected layouts, due to the enlargement of the view.
However, that scaling is not equivalent in width and height. I tried it with a 264x264 @2x resource. Given the results, I have to assume that the scaling is directly proportional to the pixels / points ratio.
Device Width scale Computed width Screenshot width
iPhone 5 640 / 640 = 1.0 264 px
iPhone 6 750 / 640 = 1.171875 309.375 309 px
iPhone 6 plus 1242 / 640 = 1.940625 512.325 512 px
Device Height scale Computed height Screenshot height
iPhone 5 1136 / 1136 = 1.0 264 px
iPhone 6 1332 / 1136 = 1.172535 309.549 310 px
iPhone 6 plus 2204 / 1136 = 1.940141 512.197 512 px
It's important to note the iPhone 6 scaling is not the same in width and height (309x310). This tends to confirm the above theory that scaling is not proportional in width and height, but uses the pixels / points ratio.
I hope this helps.
Formatting works correctly even without having to round:
"%.1f" % n
There are jQuery events like keyup and keypress which you can use with input HTML Elements. You could additionally use the blur() event.
You do not specify why you think it is wrong but I can se two dangers:
BETWEEN can be implemented differently in different databases sometimes it is including the border values and sometimes excluding, resulting in that 1 and 31 of january would end up NOTHING. You should test how you database does this.
Also, if RATE_DATE contains hours also 2010-01-31 might be translated to 2010-01-31 00:00 which also would exclude any row with an hour other that 00:00.
Have you tried somethig like this?
.showme{display: none;}
.showhim:hover .showme{display : block;}
.hideme{display:block;}
.showhim:hover .hideme{display:none;}
<div class="showhim">HOVER ME
<div class="showme">hai</div>
<div class="hideme">bye</div>
</div>
I dont know any reason why it shouldn't be possible.
Please add: CFLAGS="-lrt"
and LDFLAGS="-lrt"
// app.js or break it up into seperate files
// whatever structure is your flavor
angular.module('myApp', [])
.constant('CONFIG', {
'APP_NAME' : 'My Awesome App',
'APP_VERSION' : '0.0.0',
'GOOGLE_ANALYTICS_ID' : '',
'BASE_URL' : '',
'SYSTEM_LANGUAGE' : ''
})
.controller('GlobalVarController', ['$scope', 'CONFIG', function($scope, CONFIG) {
// If you wish to show the CONFIG vars in the console:
console.log(CONFIG);
// And your CONFIG vars in .constant will be passed to the HTML doc with this:
$scope.config = CONFIG;
}]);
In your HTML:
<span ng-controller="GlobalVarController">{{config.APP_NAME}} | v{{config.APP_VERSION}}</span>
$ which java
should give you something like
/usr/bin/java
While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event
argument to the setMaster
function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):
function AdminController($scope) {
$scope.setMaster = function(obj, $event){
console.log($event.target);
}
}
this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.
The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event
argument) would be:
<div ng-controller="AdminController">
<ul class="list-holder">
<li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
<a ng-click="setMaster(section)">{{section.name}}</a>
</li>
</ul>
<hr>
{{selected | json}}
</div>
where methods in the controller would look like this:
$scope.setMaster = function(section) {
$scope.selected = section;
}
$scope.isSelected = function(section) {
return $scope.selected === section;
}
Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/
Try this:
& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME
To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &
.
Now on the Smartgit webpage (I don't know since when) there is the possibility to download directly the .deb package. Once installed, it will upgrade automagically itself when a new version is released.
//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");
//like if you click on a link (it will be saved in the session history,
//so the back button will work as expected)
window.location.href = "http://www.google.com";
Something throws an exception of type std::bad_alloc
, indicating that you ran out of memory. This exception is propagated through until main
, where it "falls off" your program and causes the error message you see.
Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h
looks like a syntax error.
A better way of doing this is:
import subprocess
import sys
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]
The result:
print(installed_packages)
[
"Django",
"six",
"requests",
]
Check if requests
is installed:
if 'requests' in installed_packages:
# Do something
Why this way? Sometimes you have app name collisions. Importing from the app namespace doesn't give you the full picture of what's installed on the system.
Note, that proposed solution works:
pip install http://some.site/package-name.zip
or any other archive type). python setup.py install
. sudo apt install python-requests
. Cases when it might not work:
python setup.py develop
.pip install -e /path/to/package/source/
.A better way of doing this is:
import pip
installed_packages = pip.get_installed_distributions()
For pip>=10.x use:
from pip._internal.utils.misc import get_installed_distributions
Why this way? Sometimes you have app name collisions. Importing from the app namespace doesn't give you the full picture of what's installed on the system.
As a result, you get a list of pkg_resources.Distribution
objects. See the following as an example:
print installed_packages
[
"Django 1.6.4 (/path-to-your-env/lib/python2.7/site-packages)",
"six 1.6.1 (/path-to-your-env/lib/python2.7/site-packages)",
"requests 2.5.0 (/path-to-your-env/lib/python2.7/site-packages)",
]
Make a list of it:
flat_installed_packages = [package.project_name for package in installed_packages]
[
"Django",
"six",
"requests",
]
Check if requests
is installed:
if 'requests' in flat_installed_packages:
# Do something
if we use same page to add/edit via submit button like below
<input type="hidden" value="<?echo $_GET['edit_id'];?>" name="edit_id">
then we should not use
isset($_POST['edit_id'])
bcoz edit_id
is set all the time whether it is add or edit page , instead we should use check below condition
!empty($_POST['edit_id'])
There is a better way that is safer and will not slow down your application. How Excel is set up, a cell can have either a value or a formula; the formula can not refer to its own cell. Otherwise, You end up with an infinite loop, since the new value would cause another calculation... .
Use a helper column to calculate the value based on what you put in the other cell.
For Example:
Column A is a True or False, Column B contains a monetary value, Column C contains the following formula:
=B1
Now, to calculate that column B will be highlighted yellow in a conditional format only if Column A is True and Column B is greater than Zero...
=AND(A1=True,C1>0)
You can then choose to hide column C
TRIM(BOTH chr(13)||chr(10)||' ' FROM str)
You could also add this
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
to ~/.bash_profile
, then create ~/.bashrc
where you can just add more paths to PATH. An example with .
export PATH=$PATH:.
You could use IsEmpty()
function like this:
...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...
you could also use following:
If ActiveCell.Value = vbNullString Then ...
Another way to do this is to reassign df
based on a cross section of df
, using the .xs method.
>>> df
a
b c
0 1 2
1 3 4
>>> df = df.xs('a', axis=1, drop_level=True)
# 'a' : key on which to get cross section
# axis=1 : get cross section of column
# drop_level=True : returns cross section without the multilevel index
>>> df
b c
0 1 2
1 3 4
Here is an alternative method that worked for me without having to create a DirectoryInfo object. The key point is that GetFileName()
works when there is no trailing slash in the path.
var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar));
Example:
var list = Directory.EnumerateDirectories(path, "*")
.Select(p => new
{
id = "id_" + p.GetHashCode().ToString("x"),
text = Path.GetFileName(p.TrimEnd(Path.DirectorySeparatorChar)),
icon = "fa fa-folder",
children = true
})
.Distinct()
.OrderBy(p => p.text);
This is an improvement on Kennebec's answer.
function get_browser() {_x000D_
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; _x000D_
if(/trident/i.test(M[1])){_x000D_
tem=/\brv[ :]+(\d+)/g.exec(ua) || []; _x000D_
return {name:'IE',version:(tem[1]||'')};_x000D_
} _x000D_
if(M[1]==='Chrome'){_x000D_
tem=ua.match(/\bOPR|Edge\/(\d+)/)_x000D_
if(tem!=null) {return {name:'Opera', version:tem[1]};}_x000D_
} _x000D_
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];_x000D_
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}_x000D_
return {_x000D_
name: M[0],_x000D_
version: M[1]_x000D_
};_x000D_
}_x000D_
_x000D_
var browser=get_browser(); // browser.name = 'Chrome'_x000D_
// browser.version = '40'_x000D_
_x000D_
console.log(browser);
_x000D_
This way you can shield yourself from the obscurity of the code.
This works for me.
json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
Suppose JSON file is like this:
{
"emp_details":[
{
"emp_name":"John",
"emp_emailId":"[email protected]"
},
{
"emp_name":"Aditya",
"emp_emailId":"[email protected]"
}
]
}
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
#Output:
{'emp_name':'John','emp_emailId':'[email protected]'}
{'emp_name':'Aditya','emp_emailId':'[email protected]'}
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
The below code should help you out. :)
//The function is based on http://css-tricks.com/snippets/jquery/serialize-form-to-json/
<script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form.login').on('submit', function(e) {
e.preventDefault();
var formData = $(this).serializeObject();
console.log(formData);
$('.datahere').html(formData);
});
});
</script>
This is a warning for usual. You can either disable it by
#pragma warning(disable:4996)
or simply use fopen_s like Microsoft has intended.
But be sure to use the pragma before other headers.
InputStream is = getResources().getAssets().open("terms.txt");
String textfile = convertStreamToString(is);
public static String convertStreamToString(InputStream is)
throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[2048];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String text = writer.toString();
return text;
}
document.location
is an object, not a string. It returns (by default) the full path, but it actually holds more info than that.
Shortcut for solution: document.location.toString().substring(2,3);
Or use document.location.href
or window.location.href
A lot of these answers say to use vertical-align: middle;
, which gets the alignment close but for me it is still off by a few pixels. The method that I used to get true 1 to 1 alignment between the labels and radio inputs is this, with vertical-align: top;
:
label, label>input{_x000D_
font-size: 20px;_x000D_
display: inline-block;_x000D_
margin: 0;_x000D_
line-height: 28px;_x000D_
height: 28px;_x000D_
vertical-align: top;_x000D_
}
_x000D_
<h1>How are you?</h1>_x000D_
<fieldset>_x000D_
<legend>Your response:</legend>_x000D_
<label for="radChoiceGood">_x000D_
<input type="radio" id="radChoiceGood" name="radChoices" value="Good">Good_x000D_
</label>_x000D_
_x000D_
<label for="radChoiceExcellent">_x000D_
<input type="radio" id="radChoiceExcellent" name="radChoices" value="Excellent">Excellent_x000D_
</label>_x000D_
_x000D_
<label for="radChoiceOk">_x000D_
<input type="radio" id="radChoiceOk" name="radChoices" value="OK">OK_x000D_
</label>_x000D_
</fieldset>
_x000D_
SIMPLE method may not be the best for all cases
<%
if (Session["Utype"].ToString() == "1")
{
%>
<li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>
<li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
<%
}
else
{
%>
<li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
<%
}
%>
Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map
(basic implementation of a sparse matrix):
// UnorderedMapObjectAsKey.cpp
#include <iostream>
#include <vector>
#include <unordered_map>
struct Pos
{
int row;
int col;
Pos() { }
Pos(int row, int col)
{
this->row = row;
this->col = col;
}
bool operator==(const Pos& otherPos) const
{
if (this->row == otherPos.row && this->col == otherPos.col) return true;
else return false;
}
struct HashFunction
{
size_t operator()(const Pos& pos) const
{
size_t rowHash = std::hash<int>()(pos.row);
size_t colHash = std::hash<int>()(pos.col) << 1;
return rowHash ^ colHash;
}
};
};
int main(void)
{
std::unordered_map<Pos, int, Pos::HashFunction> umap;
// at row 1, col 2, set value to 5
umap[Pos(1, 2)] = 5;
// at row 3, col 4, set value to 10
umap[Pos(3, 4)] = 10;
// print the umap
std::cout << "\n";
for (auto& element : umap)
{
std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
}
std::cout << "\n";
return 0;
}
That's not the real error, here's how to find it:
Go to the hadoop jobtracker web-dashboard, find the hive mapreduce jobs that failed and look at the logs of the failed tasks. That will show you the real error.
The console output errors are useless, largely beause it doesn't have a view of the individual jobs/tasks to pull the real errors (there could be errors in multiple tasks)
Hope that helps.
In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:
DoCmd.SetWarnings False
After running all the updates, the last step in my VBA script is:
DoCmd.SetWarnings True
Hope this helps.
Restarting my ng serve
process worked for me
In case of simple example if your api is below
@POST
@Path("update_accounts")
@Consumes(MediaType.APPLICATION_JSON)
@PermissionRequired(Permissions.UPDATE_ACCOUNTS)
void createLimit(List<AccountUpdateRequest> requestList) throws RuntimeException;
where AccountUpdateRequest :
public class AccountUpdateRequest {
private Long accountId;
private AccountType accountType;
private BigDecimal amount;
...
}
then your postman request would be: http://localhost:port/update_accounts
[
{
"accountType": "LEDGER",
"accountId": 11111,
"amount": 100
},
{
"accountType": "LEDGER",
"accountId": 2222,
"amount": 300
},
{
"accountType": "LEDGER",
"accountId": 3333,
"amount": 1000
}
]
For me I solved this error just by adding this line inside repository
maven { url 'https://maven.google.com' }
From the official Swift programming guide:
Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily.
You can define it in any file and can access it in current module
anywhere.
So you can define it somewhere in the file outside of any scope. There is no need for static
and all global variables are computed lazily.
var yourVariable = "someString"
You can access this from anywhere in the current module.
However you should avoid this as Global variables are not good for application state and mainly reason of bugs.
As shown in this answer, in Swift you can encapsulate them in struct
and can access anywhere.
You can define static variables or constant in Swift also. Encapsulate in struct
struct MyVariables {
static var yourVariable = "someString"
}
You can use this variable in any class or anywhere
let string = MyVariables.yourVariable
println("Global variable:\(string)")
//Changing value of it
MyVariables.yourVariable = "anotherString"
class BooleanTester
{
boolean primitive;
Boolean object;
public static void main(String[] args) {
BooleanTester booleanTester = new BooleanTester();
System.out.println("primitive: " + booleanTester.getPrimitive());
System.out.println("object: " + booleanTester.getObject());
}
public boolean getPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
}
output:
primitive: false
object: null
This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.
Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.
I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.
Symfony is smart and knows how to make the find()
by itself :
public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
To send the id in your controller, use {{ path('your_route', {'id': guest.id}) }}
I had this problem because i was adding bundle and certificate in wrong order so maybe this could help someone else.
Before (which is wrong) :
cat ca_bundle.crt certificate.crt > bundle_chained.crt
After (which is right)
cat certificate.crt ca_bundle.crt > bundle_chained.crt
And Please don't forget to update the appropriate conf (ssl_certificate must now point to the chained crt) as
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate bundle_chained.crt;
ssl_certificate_key www.example.com.key;
...
}
From the nginx manpage:
If the server certificate and the bundle have been concatenated in the wrong order, nginx will fail to start and will display the error message:
SSL_CTX_use_PrivateKey_file(" ... /www.example.com.key") failed (SSL: error:0B080074:x509 certificate routines: X509_check_private_key:key values mismatch)
Another trivial solution would be:
from aqcron import At
from time import sleep
from datetime import datetime
# Event scheduling
event_1 = At( second=5 )
event_2 = At( second=[0,20,40] )
while True:
now = datetime.now()
# Event check
if now in event_1: print "event_1"
if now in event_2: print "event_2"
sleep(1)
And the class aqcron.At is:
# aqcron.py
class At(object):
def __init__(self, year=None, month=None,
day=None, weekday=None,
hour=None, minute=None,
second=None):
loc = locals()
loc.pop("self")
self.at = dict((k, v) for k, v in loc.iteritems() if v != None)
def __contains__(self, now):
for k in self.at.keys():
try:
if not getattr(now, k) in self.at[k]: return False
except TypeError:
if self.at[k] != getattr(now, k): return False
return True
Yes you can do like this :
Creating advanced C# custom events
or
The Simplest C# Events Example Imaginable
public class Metronome
{
public event TickHandler Tick;
public EventArgs e = null;
public delegate void TickHandler(Metronome m, EventArgs e);
public void Start()
{
while (true)
{
System.Threading.Thread.Sleep(3000);
if (Tick != null)
{
Tick(this, e);
}
}
}
}
public class Listener
{
public void Subscribe(Metronome m)
{
m.Tick += new Metronome.TickHandler(HeardIt);
}
private void HeardIt(Metronome m, EventArgs e)
{
System.Console.WriteLine("HEARD IT");
}
}
class Test
{
static void Main()
{
Metronome m = new Metronome();
Listener l = new Listener();
l.Subscribe(m);
m.Start();
}
}
Ruby version:
caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"args"=> ["--window-size=1280,960"]})
url = "http://localhost:9515" # if you are using local chrome or url = Browserstack/ saucelabs hub url if you are using cloud service providers.
Selenium::WebDriver.for(:remote, :url => url, :desired_capabilities => caps)
resize chrome is buggy in latest chromedrivers , it fails intermittanly with this failure message.
unknown error: cannot get automation extension
from timeout: cannot determine loading status
from timeout: Timed out receiving message from renderer: -65.294
(Session info: chrome=56.0.2924.76)
(Driver info: chromedriver=2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f)
And resizeTo via javascript also not supported for chrome started via selenium webdriver. So the last option was using command line switches.
I believe that this is known as "interned" strings. Python does this, so does Java, and so do C and C++ when compiling in optimized modes.
If you use two identical strings, instead of wasting memory by creating two string objects, all interned strings with the same contents point to the same memory.
This results in the Python "is" operator returning True because two strings with the same contents are pointing at the same string object. This will also happen in Java and in C.
This is only useful for memory savings though. You cannot rely on it to test for string equality, because the various interpreters and compilers and JIT engines cannot always do it.
AJAX requests are no different from GET and POST requests initiated through a <form>
element. Which means you can use $_GET and $_POST to retrieve the data.
When you're making an AJAX request (jQuery example):
// JavaScript file
elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})
It's (almost) equivalent to posting this form:
<form action="/test.php" method="post">
<input type="text" name="elements" value="1,2,9,15">
</form>
In both cases, on the server side you can read the data from the $_POST variable:
// test.php file
$elements = $_POST['elements'];
$elements = explode(',', $elements);
For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.
did not have to uninstall Java JDK - just ran installer over my existing install. Not sure what was wrong but this fixed my issue with Eclipse not starting.
The reason i like below technique because it also help me to identify the section of table.
Add Button in cell cellForRowAtIndexPath:
UIButton *selectTaskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[selectTaskBtn setFrame:CGRectMake(15, 5, 30, 30.0)];
[selectTaskBtn setTag:indexPath.section]; //Not required but may find useful if you need only section or row (indexpath.row) as suggested by MR.Tarun
[selectTaskBtn addTarget:self action:@selector(addTask:) forControlEvents:UIControlEventTouchDown];
[cell addsubview: selectTaskBtn];
Event addTask:
-(void)addTask:(UIButton*)btn
{
CGPoint buttonPosition = [btn convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
if (indexPath != nil)
{
int currentIndex = indexPath.row;
int tableSection = indexPath.section;
}
}
Hopes this help.
I had the same problem, but in my case none of this helped. In my situation every WPF project I had (including newly made projects) stopped compiling with this error. Eventually I uninstalled all the .Net frameworks then reinstalled them and things started working again. I also did a reinstall of Visual Studio, but it turned out that had no affect.
There is a 3rd party debugger in the works, it's currently in preview, but you can install the debugger Android extension in VSCode right now and get more information on it here:
If having following JSON from web service, Json Array as a response :
[3]
0: {
id: 2
name: "a561137"
password: "test"
firstName: "abhishek"
lastName: "ringsia"
organization: "bbb"
}-
1: {
id: 3
name: "a561023"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}-
2: {
id: 4
name: "a541234"
password: "hello"
firstName: "hello"
lastName: "hello"
organization: "hello"
}
have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .
List<User> list = new ArrayList<User>();
JSONArray jsonArr = new JSONArray(response);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
ObjectMapper mapper = new ObjectMapper();
User usr = mapper.readValue(jsonObj.toString(), User.class);
list.add(usr);
}
mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .
See the above definition where it states that a callback function is passed off to some other function and at some point it is called.
In C++ it is desirable to have callback functions call a classes method. When you do this you have access to the member data. If you use the C way of defining a callback you will have to point it to a static member function. This is not very desirable.
Here is how you can use callbacks in C++. Assume 4 files. A pair of .CPP/.H files for each class. Class C1 is the class with a method we want to callback. C2 calls back to C1's method. In this example the callback function takes 1 parameter which I added for the readers sake. The example doesn't show any objects being instantiated and used. One use case for this implementation is when you have one class that reads and stores data into temporary space and another that post processes the data. With a callback function, for every row of data read the callback can then process it. This technique cuts outs the overhead of the temporary space required. It is particularly useful for SQL queries that return a large amount of data which then has to be post-processed.
/////////////////////////////////////////////////////////////////////
// C1 H file
class C1
{
public:
C1() {};
~C1() {};
void CALLBACK F1(int i);
};
/////////////////////////////////////////////////////////////////////
// C1 CPP file
void CALLBACK C1::F1(int i)
{
// Do stuff with C1, its methods and data, and even do stuff with the passed in parameter
}
/////////////////////////////////////////////////////////////////////
// C2 H File
class C1; // Forward declaration
class C2
{
typedef void (CALLBACK C1::* pfnCallBack)(int i);
public:
C2() {};
~C2() {};
void Fn(C1 * pThat,pfnCallBack pFn);
};
/////////////////////////////////////////////////////////////////////
// C2 CPP File
void C2::Fn(C1 * pThat,pfnCallBack pFn)
{
// Call a non-static method in C1
int i = 1;
(pThat->*pFn)(i);
}
I would recommend the use of IPNetwork Library https://github.com/lduchosal/ipnetwork. As of version 2, it supports IPv4 and IPv6 as well.
IPv4
IPNetwork ipnetwork = IPNetwork.Parse("192.168.0.1/25");
Console.WriteLine("Network : {0}", ipnetwork.Network);
Console.WriteLine("Netmask : {0}", ipnetwork.Netmask);
Console.WriteLine("Broadcast : {0}", ipnetwork.Broadcast);
Console.WriteLine("FirstUsable : {0}", ipnetwork.FirstUsable);
Console.WriteLine("LastUsable : {0}", ipnetwork.LastUsable);
Console.WriteLine("Usable : {0}", ipnetwork.Usable);
Console.WriteLine("Cidr : {0}", ipnetwork.Cidr);
Output
Network : 192.168.0.0
Netmask : 255.255.255.128
Broadcast : 192.168.0.127
FirstUsable : 192.168.0.1
LastUsable : 192.168.0.126
Usable : 126
Cidr : 25
Have fun !
I increased the virtual device SD card size from 500MB to 2GiB, the problem solved.
On Windows 10, I had the same problem. PIP 19
was already installed in my system but wasn't showing up. The error was No Module Found
.
python -m pip uninstall pip
python -m pip install pip==9.0.3
Downgrading pip
to 9.0.3 worked fine for me.
v1.42 is adding some nice refinements to how folds look and function. See https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_42.md#folded-range-highlighting:
Folded Range Highlighting
Folded ranges now are easier to discover thanks to a background color for all folded ranges.
Fold highlight color Theme: Dark+
The feature is controled by the setting editor.foldingHighlight and the color can be customized with the color editor.foldBackground.
"workbench.colorCustomizations": { "editor.foldBackground": "#355000" }
Folding Refinements
Shift + Click
on the folding indicator first only folds the inner ranges.Shift + Click
again (when all inner ranges are already folded) will also fold the parent.Shift + Click
again unfolds all.
When using the Fold command (kb(
editor.fold
))] on an already folded range, the next unfolded parent range will be folded.
use jQuery's $.getJSON
$.getJSON('mydata.json', function(data) {
//do stuff with your data here
});
If your flavour of markdown is kramdown, then you can set css class like this:
{:.nameofclass}
paragraph is here
Then in you css file, you set the css like this:
.nameofclass{
color: #000;
}
This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.
The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin
and xmax
are in the range [0,1].
On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin
and xmax
are the in the range of data limit of x axis.
Let's take a concrete example,
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')
plt.show()
It will produce the following plot:
The value for xmin
and xmax
are the same for the axhline
and hlines
method. But the length of produced line is different.
Try ::after on previous element.
Another library to consider is MySqlConnector, https://mysqlconnector.net/. Mysql.Data is under a GPL license, whereas MySqlConnector is MIT.
Using React on my IPad, type="number"
does not work perfectly for me.
For my floating point numbers in the range between 99.99999 - .00000 I use the regular expression (^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)
. The first group (...)
is true for all positive two digit numbers without the floating point (e.g. 23), |
or e.g. .12345 for the second group (...)
. You can adopt it for any positive floating point number by simply changing the range {0,2}
or {0,5}
respectively.
<input
className="center-align"
type="text"
pattern="(^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)"
step="any"
maxlength="7"
validate="true"
/>
Here is another way with awk
:
awk 'ORS=NR%2?FS:RS' file
$ cat file
KEY 4048:1736 string
3
KEY 0:1772 string
1
KEY 4192:1349 string
1
KEY 7329:2407 string
2
KEY 0:1774 string
1
$ awk 'ORS=NR%2?FS:RS' file
KEY 4048:1736 string 3
KEY 0:1772 string 1
KEY 4192:1349 string 1
KEY 7329:2407 string 2
KEY 0:1774 string 1
As indicated by Ed Morton in the comments, it is better to add braces for safety and parens for portability.
awk '{ ORS = (NR%2 ? FS : RS) } 1' file
ORS
stands for Output Record Separator. What we are doing here is testing a condition using the NR
which stores the line number. If the modulo of NR
is a true value (>0) then we set the Output Field Separator to the value of FS
(Field Separator) which by default is space, else we assign the value of RS
(Record Separator) which is newline.
If you wish to add ,
as the separator then use the following:
awk '{ ORS = (NR%2 ? "," : RS) } 1' file
I think it will work
for (int i = 1; i <= broj_ds; i++ )
{
QuantityInIssueUnit_value = dr_art_line_2[i]["Column"];
QuantityInIssueUnit_uom = dr_art_line_2[i]["Column"];
}
Just a note:
W3C has no problem with button inside of link tag, so it is just another MS sub-standard.
Answer:
Use surrogate button, unless you want to go for a full image.
Surrogate button can be put into tag (safer, if you use spans, not divs).
It can be styled to look like button, or anything else.
It is versatile - one piece of css code powers all instances - just define CSS once and from that point just copy and paste html instance wherever your code requires it.
Every button can have its own label - great for multi-lingual pages (easier that doing pictures for every language - I think) - also allows to propagate instances all over your script easier.
Adjusts its width to label length - also takes fixed width if it is how you want it.
IE7 is an exception to above - it must have width, or will make this button from edge to edge - alternatively to giving it width, you can float button left
- css for IE7:
a. .width:150px; (make note of dot before property, I usually target IE7 by adding such dot - remove dot and property will be read by all browsers)
b. text-align:center; - if you have fixed width, you have to have this to center text/label
c. cursor:pointer; - all IE must have this to show link pointer correctly - good browsers do not need it
You can go step forward with this code and use CSS3 to style it, instead of using images:
a. radius for round corners (limitation: IE will show them square)
b. gradient to make it "button like" (limitation: opera does not support gradients, so remember to set standard background colour for this browser)
c. use :hover pclass to change button states depending on mouse pointer position etc. - you can apply it to text label only, or whole button
.button_surrogate span { margin:0; display:block; height:25px; text-align:center; cursor:pointer; .width:150px; background:url(left_button_edge.png) left top no-repeat; }
.button_surrogate span span { display:block; padding:0 14px; height:25px; background:url(right_button_edge.png) right top no-repeat; }
.button_surrogate span span span { display:block; overflow:hidden; padding:5px 0 0 0; background:url(button_connector.png) left top repeat-x; }
HTML code below (button instance):
<a href="#">
<span class="button_surrogate">
<span><span><span>YOUR_BUTTON_LABEL</span></span></span>
</span>
</a>
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
You are mixing tabs and spaces. Don't do that. Specifically, the __init__
function body is indented with tabs while your on_data
method is not.
Here is a screenshot of your code in my text editor; I set the tab stop to 8 spaces (which is what Python uses) and selected the text, which causes the editor to display tabs with continuous horizontal lines:
You have your editor set to expanding tabs to every fourth column instead, so the methods appear to line up.
Run your code with:
python -tt scriptname.py
and fix all errors that finds. Then configure your editor to use spaces only for indentation; a good editor will insert 4 spaces every time you use the TAB key.
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
A callback function is simply a function you pass into another function so that function can call it at a later time. This is commonly seen in asynchronous APIs; the API call returns immediately because it is asynchronous, so you pass a function into it that the API can call when it's done performing its asynchronous task.
The simplest example I can think of in JavaScript is the setTimeout()
function. It's a global function that accepts two arguments. The first argument is the callback function and the second argument is a delay in milliseconds. The function is designed to wait the appropriate amount of time, then invoke your callback function.
setTimeout(function () {
console.log("10 seconds later...");
}, 10000);
You may have seen the above code before but just didn't realize the function you were passing in was called a callback function. We could rewrite the code above to make it more obvious.
var callback = function () {
console.log("10 seconds later...");
};
setTimeout(callback, 10000);
Callbacks are used all over the place in Node because Node is built from the ground up to be asynchronous in everything that it does. Even when talking to the file system. That's why a ton of the internal Node APIs accept callback functions as arguments rather than returning data you can assign to a variable. Instead it will invoke your callback function, passing the data you wanted as an argument. For example, you could use Node's fs
library to read a file. The fs
module exposes two unique API functions: readFile
and readFileSync
.
The readFile
function is asynchronous while readFileSync
is obviously not. You can see that they intend you to use the async calls whenever possible since they called them readFile
and readFileSync
instead of readFile
and readFileAsync
. Here is an example of using both functions.
Synchronous:
var data = fs.readFileSync('test.txt');
console.log(data);
The code above blocks thread execution until all the contents of test.txt
are read into memory and stored in the variable data
. In node this is typically considered bad practice. There are times though when it's useful, such as when writing a quick little script to do something simple but tedious and you don't care much about saving every nanosecond of time that you can.
Asynchronous (with callback):
var callback = function (err, data) {
if (err) return console.error(err);
console.log(data);
};
fs.readFile('test.txt', callback);
First we create a callback function that accepts two arguments err
and data
. One problem with asynchronous functions is that it becomes more difficult to trap errors so a lot of callback-style APIs pass errors as the first argument to the callback function. It is best practice to check if err
has a value before you do anything else. If so, stop execution of the callback and log the error.
Synchronous calls have an advantage when there are thrown exceptions because you can simply catch them with a try/catch
block.
try {
var data = fs.readFileSync('test.txt');
console.log(data);
} catch (err) {
console.error(err);
}
In asynchronous functions it doesn't work that way. The API call returns immediately so there is nothing to catch with the try/catch
. Proper asynchronous APIs that use callbacks will always catch their own errors and then pass those errors into the callback where you can handle it as you see fit.
In addition to callbacks though, there is another popular style of API that is commonly used called the promise. If you'd like to read about them then you can read the entire blog post I wrote based on this answer here.
$('.tooltip').animate({ opacity: 1, top: "-10px" }, 'slow');
However, this doesn't appear to work on display: none
elements (as fadeIn
does). So, you might need to put this beforehand:
$('.tooltip').css('display', 'block');
$('.tooltip').animate({ opacity: 0 }, 0);
Koen's answer doesn't exactly centers the element.
The proper way is to use CCS3 transform
property. Although it's not supported in some old browsers. And we don't even need to set a fixed or relative width
.
.centered {
position: fixed;
left: 50%;
transform: translate(-50%, 0);
}
Working jsfiddle comparison here.
As per PHP Documentation,
Thread Safety means that binary can work in a multithreaded webserver context, such as Apache 2 on Windows. Thread Safety works by creating a local storage copy in each thread, so that the data won't collide with another thread.
So what do I choose? If you choose to run PHP as a CGI binary, then you won't need thread safety, because the binary is invoked at each request. For multithreaded webservers, such as IIS5 and IIS6, you should use the threaded version of PHP.
Following Libraries are not thread safe. They are not recommended for use in a multi-threaded environment.
You will have to use Array.find
or Array.filter
or Array.forEach
.
Since you value is array and you need position of element, you will have to iterate over it.
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var index = -1;
var val = "allInterests"
var filteredObj = data.find(function(item, i){
if(item.name === val){
index = i;
return i;
}
});
console.log(index, filteredObj);
_x000D_
var data = [{"name":"placeHolder","section":"right"},{"name":"Overview","section":"left"},{"name":"ByFunction","section":"left"},{"name":"Time","section":"left"},{"name":"allFit","section":"left"},{"name":"allbMatches","section":"left"},{"name":"allOffers","section":"left"},{"name":"allInterests","section":"left"},{"name":"allResponses","section":"left"},{"name":"divChanged","section":"right"}];
var val = "allInterests"
var index = data.findIndex(function(item, i){
return item.name === val
});
console.log(index);
_x000D_
Default Array.indexOf()
will match searchValue to current element and not its properties. You can refer Array.indexOf - polyfill on MDN
overcommit_memory
Controls overcommit of system memory, possibly allowing processes to allocate (but not use) more memory than is actually available.
0 - Heuristic overcommit handling. Obvious overcommits of address space are refused. Used for a typical system. It ensures a seriously wild allocation fails while allowing overcommit to reduce swap usage. root is allowed to allocate slighly more memory in this mode. This is the default.
1 - Always overcommit. Appropriate for some scientific applications.
2 - Don't overcommit. The total address space commit for the system is not permitted to exceed swap plus a configurable percentage (default is 50) of physical RAM. Depending on the percentage you use, in most situations this means a process will not be killed while attempting to use already-allocated memory but will receive errors on memory allocation as appropriate.
Ideally you should do both.
First Hash the pass password for the one way security. Use a salt for extra security.
Then encrypt the hash to defend against dictionary attacks if your database of password hashes is compromised.
Fitting IFRAME contents is kind of an easy thing to find on Google. Here's one solution:
<script type="text/javascript">
function autoIframe(frameId) {
try {
frame = document.getElementById(frameId);
innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
objToResize = (frame.style) ? frame.style : frame;
objToResize.height = innerDoc.body.scrollHeight + 10;
}
catch(err) {
window.status = err.message;
}
}
</script>
This of course doesn't solve the cross-domain problem you are having... Setting document.domain
might help if these sites are in the same place. I don't think there is a solution if you are iframe-ing random sites.
No, but you can install an isolated Python build (such as ActivePython) under your $HOME
directory.
This approach is the fastest, and doesn't require you to compile Python yourself.
(as a bonus, you also get to use ActiveState's binary package manager)
Create the user with a password :
http://www.postgresql.org/docs/current/static/sql-createuser.html
CREATE USER name [ [ WITH ] option [ ... ] ]
where option can be:
SUPERUSER | NOSUPERUSER
| CREATEDB | NOCREATEDB
| CREATEROLE | NOCREATEROLE
| CREATEUSER | NOCREATEUSER
| INHERIT | NOINHERIT
| LOGIN | NOLOGIN
| REPLICATION | NOREPLICATION
| CONNECTION LIMIT connlimit
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
| VALID UNTIL 'timestamp'
| IN ROLE role_name [, ...]
| IN GROUP role_name [, ...]
| ROLE role_name [, ...]
| ADMIN role_name [, ...]
| USER role_name [, ...]
| SYSID uid
Then grant the user rights on a specific database :
http://www.postgresql.org/docs/current/static/sql-grant.html
Example :
grant all privileges on database db_name to someuser;
I'm really fond of SPL Library, they offer iterator's, including RecursiveDirectoryIterator.
preg_replace("/[[:blank:]]+/"," ",$input)
Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.
If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.
The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.
How we can count the duplicated values?? either it is repeated 2 times or greater than 2. just count them, not group wise.
as simple as
select COUNT(distinct col_01) from Table_01
CSS 3 introduces rgba colour, and you can combine it with graphics for a backwards compatible solution.
There are plenty of free portable GUI libraries, each with its own strengths and weaknesses:
Especially Qt has nice tutorials and tools which help you getting started. Enjoy!
Note, however, that you should avoid platform specific functionality such as the Win32 API or MFC. That ties you unnecessarily on a specific platform with almost no benefits.
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
Don't need a regex
.
string[: string.find(' ')]
It's not possible to do it just like that, but you can overlay an opaque div between the div with the background-image and the text and fade that one out, hence giving the appearance that the background is fading in.
Download the latest CMake Mac binary distribution here: https://cmake.org/download/ (current latest is: https://cmake.org/files/v3.17/cmake-3.17.1-Darwin-x86_64.dmg)
Double click the downloaded .dmg file to install it. In the window that pops up, drag the CMake icon into the Application folder.
Add this line to your .bashrc file: PATH="/Applications/CMake.app/Contents/bin":"$PATH"
Reload your .bashrc file: source ~/.bashrc
Verify the latest cmake version is installed: cmake --version
You can launch the CMake GUI by clicking on LaunchPad and typing cmake. Click on the CMake icon that appears.
I was totally unable to do this in NP v6.9. I found it easy enough on Msoft Word (2K).
Open the doc, go to edit->replace.
Then in the bottom of the search box, click "more" then find the "Special" button and they have several things for you. For Dos style, I used the "paragraph" one. This is a cr lf pair in windows land.
I think you can simple call like this, this will give you result value.
this.$route.query.page
Look image $route is object in Vue Instance and you can access with this keyword and next you can select object properties like above one :
Have a look Vue-router document for selecting queries value :
The XML document:
<Home>
<Addr>
<Street>ABC</Street>
<Number>5</Number>
<Comment>BLAH BLAH BLAH <br/><br/>ABC</Comment>
</Addr>
</Home>
The XPath expression:
//*[contains(text(), 'ABC')]
//*
matches any descendant element of the root node. That is, any element but the root node.
[...]
is a predicate, it filters the node-set. It returns nodes for which ...
is true
:
A predicate filters a node-set [...] to produce a new node-set. For each node in the node-set to be filtered, the PredicateExpr is evaluated [...]; if PredicateExpr evaluates to true for that node, the node is included in the new node-set; otherwise, it is not included.
contains('haystack', 'needle')
returns true
if haystack
contains needle
:
Function: boolean contains(string, string)
The contains function returns true if the first argument string contains the second argument string, and otherwise returns false.
But contains()
takes a string as its first parameter. And it's passed nodes. To deal with that every node or node-set passed as the first parameter is converted to a string by the string()
function:
An argument is converted to type string as if by calling the string function.
string()
function returns string-value
of the first node:
A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.
string-value
of an element node:
The string-value of an element node is the concatenation of the string-values of all text node descendants of the element node in document order.
string-value
of a text node:
The string-value of a text node is the character data.
So, basically string-value
is all text that is contained in a node (concatenation of all descendant text nodes).
text()
is a node test that matches any text node:
The node test text() is true for any text node. For example, child::text() will select the text node children of the context node.
Having that said, //*[contains(text(), 'ABC')]
matches any element (but the root node), the first text node of which contains ABC
. Since text()
returns a node-set that contains all child text nodes of the context node (relative to which an expression is evaluated). But contains()
takes only the first one. So for the document above the path matches the Street
element.
The following expression //*[text()[contains(., 'ABC')]]
matches any element (but the root node), that has at least one child text node, that contains ABC
. .
represents the context node. In this case, it's a child text node of any element but the root node. So for the document above the path matches the Street
, and the Comment
elements.
Now then, //*[contains(., 'ABC')]
matches any element (but the root node) that contains ABC
(in the concatenation of the descendant text nodes). For the document above it matches the Home
, the Addr
, the Street
, and the Comment
elements. As such, //*[contains(., 'BLAH ABC')]
matches the Home
, the Addr
, and the Comment
elements.
Copied from my answer here: https://stackoverflow.com/a/9368199/485088
Run
ldconfig
as root to update the cache - if that still doesn't help, you need to add the path to the fileld.so.conf
(just type it in on its own line) or better yet, add the entry to a new file (easier to delete) in directoryld.so.conf.d
.
I don't think there is a way to tell which program to use from just the .db extension. It could even be an encrypted database which can't be opened. You can MS Access, or a sqlite manager.
Edit: Try to rename the file to .txt and open it with a text editor. The first couple of words in the file could tell you the DB Type.
If it is a SQLite database, it will start with "SQLite format 3"
I faced same issue but now i am happy to resolve this issue.
npm i core-js
index.js
file.
import core-js
You can create public static method in fragment where you will get static reference of that fragment and then pass data to that function and set that data to argument in same method and get data via getArgument on oncreate method of fragment, and set that data to local variables.
>>> import pandas
>>> pandas.DataFrame(data, teams_list, teams_list)
Man Utd Man City T Hotspur
Man Utd 1 2 1
Man City 0 1 0
T Hotspur 2 4 2
import itertools
ab = itertools.chain(['it'], ['was'], ['annoying'])
list(ab)
Just another method....
To Increase request time out add this to web.config
<system.web>
<httpRuntime executionTimeout="180" />
</system.web>
and for a specific page add this
<location path="somefile.aspx">
<system.web>
<httpRuntime executionTimeout="180"/>
</system.web>
</location>
The default is 90 seconds for .NET 1.x.
The default 110 seconds for .NET 2.0 and later.
Try this.
public string Post(FormDataCollection form) {
string par1 = form.Get("par1");
// ...
}
It works for me with webapi 2
This code is work for me
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
// add your action here that you want
return true;
}
else if (id==R.id.login)
{
// add your action here that you want
}
return super.onOptionsItemSelected(item);
}
git log --grep=<pattern>
Limit the commits output to ones with log message that matches the
specified pattern (regular expression).