Yes, it works when with the command npm install --no-optional
Using environment:
To be short, use:
write-output "your text" | out-file -append -encoding utf8 "filename"
The problem is that the number of <th> tags need to match the number of columns in the configuration (the array with the key "columns"). If there are fewer <th> tags than columns specified, you get this slightly cryptical error message.
(the correct answer is already present as a comment but I'm repeating it as an answer so it's easier to find - I didn't see the comments)
I solved this issue by removing all the NuGet packages from solution and reinstalling them. One of the NuGet Packages was dependent upon NewtonSoft and it was not showing in references
Hello @sahil I update your answer for swift 3
let imageDataDict:[String: UIImage] = ["image": image]
// post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call
// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
// handle notification
func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage{
// do something with your image
}
}
}
Hope it's helpful. Thanks
I removed android platforms and installed again then worked. I wrote these lines in command window:
cordova platform remove android
then
cordova platform add android
I think this:
text.delete("1.0", tkinter.END)
Or if you did from tkinter import *
text.delete("1.0", END)
That should work
Since you didn't mention the version of Eclipse, I advice you to download the latest version of Eclipse Luna
which comes with Java 8 support by default.
Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.
The simplest and easiest way is to execute your particular script with -NoExit
param.
1.Open run box by pressing:
Win + R
2.Then type into input prompt:
PowerShell -NoExit "C:\folder\script.ps1"
and execute.
For me the command:
set PATH=%PATH%;C:\Python34\Scripts
worked immediately (try after echo %PATH% and you will see that your path has the value C:\Python34\Scripts).
Thanks to: Adding a directory to the PATH environment variable in Windows
You Can simply Use One Jsp Page To accomplish the task.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
From:
it could be:
.html()
In an HTML document, .html()
can be used to get the contents of any element.
.text()
Unlike the .html()
method, .text()
can be used in both XML and HTML documents. The result of the .text()
method is a string containing the combined text of all matched elements.
.val()
The .val()
method is primarily used to get the values of form elements such as input
, select
and textarea
. When called on an empty collection, it returns undefined
.
Try to modify your eclipse.ini with below
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20120913-144807
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Dhelp.lucene.tokenizer=standard
-Xms2G
-Xmx3G
-XX:MaxPermSize=2G
-XX:+UseCompressedOops
-XX:+UseParallelGC
Once you open your eclipse you can try below
Looks like your application consumes more memory than allocated (Default). I will try two things
As suggested by Harmlezz increase your memory allocation to JVM to -Xms2g -Xmx2g (If needed increase it more and try it out)
Download eclipse memory analyzer and check for what causing memory leak OR even you can use JConsole to see JVM memory utilization in order to figure out application memory leak issue.
Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.
A relatively short path to specifying a Powershell script to execute at startup in Windows could be:
shell:startup
Create a new shortcut by rightclick and in context menu choose menu item: New=>Shortcut
Create a shortcut to your script, e.g:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "C:\Users\someuser\Documents\WindowsPowerShell\Scripts\somesscript.ps1"
Note the use of -NoProfile In case you put a lot of initializing in your $profile file, it is inefficient to load this up to just run a Powershell script. The -NoProfile will skip loading your profile file and is smart to specify, if it is not necessary to run it before the Powershell script is to be executed.
Here you see such a shortcut created (.lnk file with a Powershell icon with shortcut glyph):
With recent matplotlib versions you might want to try Constrained Layout. This does not work with plt.subplot()
however, so you need to use plt.subplots()
instead:
fig, axs = plt.subplots(4, 4, constrained_layout=True)
NullPointerException with JSP can also happen if:
A getter returns a non-public inner class.
This code will fail if you remove Getters's access modifier or make it private or protected.
JAVA:
package com.myPackage;
public class MyClass{
//: Must be public or you will get:
//: org.apache.jasper.JasperException:
//: java.lang.NullPointerException
public class Getters{
public String
myProperty(){ return(my_property); }
};;
//: JSP EL can only access functions:
private Getters _get;
public Getters get(){ return _get; }
private String
my_property;
public MyClass(String my_property){
super();
this.my_property = my_property;
_get = new Getters();
};;
};;
JSP
<%@ taglib uri ="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="com.myPackage.MyClass" %>
<%
MyClass inst = new MyClass("[PROP_VALUE]");
pageContext.setAttribute("my_inst", inst );
%><html lang="en"><body>
${ my_inst.get().myProperty() }
</body></html>
This may be an old post, but if anyone is still facing this issue after trying all the above mentioned steps, ensure whether the default path of PowerShell module is specified under the "PSModulePath" environment variable.
The default path should be "%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\"
Rearrange the regex to:
/^(\d{4})([\/-])(\d{1,2})\2(\d{1,2})$/
I have done a little more than just rearrange the terms, I've also made it so that it won't accept "broken" dates like yyyy-mm/dd
.
After that, you need to adjust your dtMonth
etc. variables like so:
dtYear = dtArray[1];
dtMonth = dtArray[3];
dtDay = dtArray[4];
After that, the code should work just fine.
To achieve "Run as Administrator" functionality I implemented the flag:
-ExecutionPolicy Bypass
Which only seems to take effect when executing Powershell files. So I dropped my command into .ps1 file, run it with -ExecutionPolicy Bypass, and now my scheduled task is behaving as expected.
Program: Powershell.exe
Add Arguments: -ExecutionPolicy Bypass -File C:\pscommandFile.ps1
This is a slight variation that worked better for me.
$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"
$xl = new-object -comobject excel.application
$xl.visible = $false
$Workbook = $xl.workbooks.open($CSV)
$Worksheets = $Workbooks.worksheets
$Workbook.SaveAs($XLS,1)
$Workbook.Saved = $True
$xl.Quit()
If you are in a submodule, don't forget to declare the module in main app. ie :
<scrip>
angular.module('mainApp', ['subModule1', 'subModule2']);
angular.module('subModule1')
.controller('MyController', ['$scope', function($scope) {
$scope.moduleName = 'subModule1';
}]);
</script>
...
<div ng-app="mainApp">
<div ng-controller="MyController">
<span ng-bind="moduleName"></span>
</div>
If you don't declare subModule1 in mainApp, you will got a "[ng:areq] Argument "MyController" is not a function, got undefined.
Basically the same solution as provided by Rutger Kassies, but using a more pythonic syntax:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
data = np.arange(250, 260)
for ax, d in zip(axs.ravel(), data):
ax.contourf(np.random.rand(10,10), 5, cmap=plt.cm.Oranges)
ax.set_title(str(d))
Had a similar problem when starting apache jmeter on windows 8 64 bit:
[]apache-jmeter-2.13\bin>jmeter
java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.
Successfully used Dennis Traub solution, with Mkorsch explanations. Or you can create a file with the extension "reg" and write into it the following:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Prefs]
... then execute it.
You should use bootstrap column nesting.
See Bootstrap 3 or Bootstrap 4:
<div class="row">
<div class="col-md-5">Span 5</div>
<div class="col-md-3">Span 3<br />second line</div>
<div class="col-md-2">
<div class="row">
<div class="col-md-12">Span 2</div>
</div>
<div class="row">
<div class="col-md-12">Span 2</div>
</div>
</div>
<div class="col-md-2">Span 2</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12">Span 6</div>
<div class="col-md-12">Span 6</div>
</div>
</div>
<div class="col-md-6">Span 6</div>
</div>
http://jsfiddle.net/DRanJ/125/
(In Fiddle screen, enlarge your test screen to see the result, because I'm using col-md-*, then responsive stacks columns)
Note: I am not sure that BS2 allows columns nesting, but in the answer of Paul Keister, the columns nesting is not used. You should use it and avoid to reinvente css while bootstrap do well.
The columns height are auto, if you add a second line (like I do in my example), column height adapt itself.
While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print
, or otherwise send Unicode strings to stdout
, and it's attached to a console/tty, Python has to encode it.
The error message indirectly tells you what character set Python was trying to use:
File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
This means the charset is cp850
.
You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850')
. Or you can look up cp850 online (e.g., at Wikipedia).
It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'
.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)
But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:
>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'
So, how do you print a string that won't print on your console?
You can replace every print
function with something like this:
>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?
… but that's going to get pretty tedious pretty fast.
The simple thing to do is to just set the error handler on sys.stdout
:
>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?
For printing to a file, things are pretty much the same, except that you don't have to set f.errors
after the fact, you can set it at construction time. Instead of this:
with open('path', 'w', encoding='cp850') as f:
Do this:
with open('path', 'w', encoding='cp850', errors='replace') as f:
… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:
with open('path', 'w', encoding='utf-8') as f:
Window > Show view > Server
or right click on the server in "Servers" view, select "Properties".You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.
I spent hours on this, and the solution was:
A simple solution that springs to mind is to have a String
block of spaces:
String indent = " "; // 20 spaces.
When printing out a string, compute the actual indent and add it to the end:
String output = "Newspaper";
output += indent.substring(0, indent.length - output.length);
This will mediate the number of spaces to the string, and put them all in the same column.
Start off by opening a cmd.exe session, changing directory to the "program files" directory that has the javac.exe executable and running .\javac.exe.
If that doesn't work, reinstall java. If that works, odds are you will find (in doing that task) that you've installed a 64 bit javac.exe
, or a slightly different release number of javac.exe
, or in a different drive, etc. and selecting the right entry in your path will become child's play.
Only use the semicolon between directories in the PATH environment variable, and remember that in some systems, you need to log out and log back in before the new environment variable is accessible to all environments.
Somewhere the code--either your code or a jQuery plugin--is calling $.browser
to get the current browser type.
However, early has year the $.browser
function was deprecated. Since then some bugs have been filed against it but because it is deprecated, the jQuery team has decided not to fix them. I've decided not to rely on the function at all.
I don't see any references to $.browser
in your code, so the problem probably lies in one of your plugins. To find it, look at the source code for each plugin that you've referenced with a <script>
tag.
As for how to fix it: well, it depends on the context. E.g., maybe there's an updated version of the problematic plugin. Or perhaps you can use another plugin that does something similar but doesn't depend on $.browser
.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table id="myTable" cellpadding="2" cellspacing="2" border="1" onclick="tester()"></table>
<script>
var student;
for (var j = 0; j < 10; j++) {
student = {
name: "Name" + j,
rank: "Rank" + j,
stuclass: "Class" + j,
};
var table = document.getElementById("myTable");
var row = table.insertRow(j);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = student.name,
cell2.innerHTML = student.rank,
cell3.innerHTML = student.stuclass;
}
</script>
</body>
</html>
You can also try closing other programs. :)
It's pretty simple, but worked for me. In my case the VM just don't had enough memory to run, and i got the same message. So i had to clean up the ram, by closing unnecessary programs.
There is not official api support which means that it is not documented for the public and the libraries may change at any time. I realize you don't want to leave the application but here's how you do it with an intent for anyone else wondering.
public void sendData(int num){
String fileString = "..."; //put the location of the file here
Intent mmsIntent = new Intent(Intent.ACTION_SEND);
mmsIntent.putExtra("sms_body", "text");
mmsIntent.putExtra("address", num);
mmsIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(fileString)));
mmsIntent.setType("image/jpeg");
startActivity(Intent.createChooser(mmsIntent, "Send"));
}
I haven't completely figured out how to do things like track the delivery of the message but this should get it sent.
You can be alerted to the receipt of mms the same way as sms. The intent filter on the receiver should look like this.
<intent-filter>
<action android:name="android.provider.Telephony.WAP_PUSH_RECEIVED" />
<data android:mimeType="application/vnd.wap.mms-message" />
</intent-filter>
Try to modify the eclipse.ini
so that both Xms
and Xmx
are of the same value:
-Xms6000m
-Xmx6000m
This should force the Eclipse's VM to allocate 6GB
of heap right from the beginning.
But be careful about either using the eclipse.ini
or the command-line ./eclipse/eclipse -vmargs ...
. It should work in both cases but pick one and try to stick with it.
After a long struggle, I've switched my node architecture to x86 and it worked like a charm.
use like this your inline css
<td width="178" rowspan="3" valign="top"
align="right" background="images/left.jpg"
style="background-repeat:background-position: right top;">
</td>
The following code allows you to specify the row/column number and get the resulting cell value:
WebDriver driver = new ChromeDriver();
WebElement base = driver.findElement(By.className("Table"));
tableRows = base.findElements(By.tagName("tr"));
List<WebElement> tableCols = tableRows.get([ROW_NUM]).findElements(By.tagName("td"));
String cellValue = tableCols.get([COL_NUM]).getText();
I had the same requirement and I have done this in following way.You also can try out this..
Use loadData method
web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");
movDirector movProducer like all are my string variable.
In short i retain custom styling for my url.
The solution of using a list of axes by abevieiramota works very well until you use only one row of images, as pointed out in the comments. Using a reasonable aspect ratio for figsize
helps, but is still far from perfect. For example:
import numpy as np
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9.75, 3))
for ax in axes.flat:
im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()
The colorbar function provides the shrink
parameter which is a scaling factor for the size of the colorbar axes. It does require some manual trial and error. For example:
fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.75)
'&' --> '&'
'<' --> '<'
'>' --> '>'
If you are using dynamic web project then make sure you have added the jar file as commons-logging-1.2.jar in "WebContent > WEB-INF > lib" folder.
Along with you can do few more step as:
Right click on project > Properties > Targeted Runtimes > Choose Apache Tomcat server from list > Apply > Ok.
Go to Servers tab > Right click on server configured > Properties > General > Switch location(eg- /Servers/Tomcat/.....) > Apply > Ok.
That's all!
look into org.eclipse.wst.common.component file in your web project in eclipse.
< wb-module deploy-name="PROJECT_NAME">
check the PROJECT_NAME. It might got messed up. Similarly look into .project file.
Hope this helps!!
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
LibGDX is one of the best engines I've ever used, works on almost all platforms, and performs twice as fast as cocos2d-x in most tests I've done. You can use any JVM language you like. Here's a 13 part tutorial in Java, and here's a bunch using jruby. There's a good skeletal animation tool that works with it here, and it has baked in support for tiled TMX maps as well. The ui framework is awesome, and it has a scene graph and actor style API similar to cocos2d scenes, sprites and actions. The community is awesome, updates are frequent, and the documentation is good. Don't let the java part scare you, it's fast, and you can use jruby or scala or whatever you like. I highly recommend it for 2d or 3d work, it supports both.
You have to set both layout_gravity and layout_columntWeight on your columns
<android.support.v7.widget.GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
<TextView android:text="??? ???"
app:layout_gravity="fill_horizontal"
app:layout_columnWeight="1"
/>
</android.support.v7.widget.GridLayout>
In my case, I didnt mark for instalation the mingw32-gcc-g++ package in the installation manager, that's why eclipse didn't know it.
Needed to go to the instalation manager, mark it (in basic setup tab) and update catalogue
Probably there are some files inside C:\cygwin\bin called xxxxxmake.exe
, try renaming it to make.exe
This type of errors occur basically due to use of different versions of Java with different version of Eclipse.
Suppose you are installing the 64-bit JDK on your system. Then make sure you install the 64-bit versioned Eclipse with it.
And if you are installing the 32-bit JDK on your system then make sure you install 32-bit versioned Eclipse with it.
I had the similar problem. I have installed the 32-bit JDK and was trying to use 64-bit Eclipse.
But when I installed the 64-bit JDK on my system then Eclipse started working without any problem.
It is advised to better install the 32-bit version of Java along with the 32-bit version Eclipse on a system with a 32-bit configuration and similarly for 64-bit systems.
This helps to increase performance of the system.
I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:
String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);
byte[] b = baos.toByteArray();
encImage = Base64.encodeToString(b, Base64.DEFAULT);
One of the most beautiful ways in my opinion (since it is now commonly available) is using behaviours.
It requires:
Microsoft.Xaml.Behaviors.Wpf
xaml code:
xmlns:Interactions="http://schemas.microsoft.com/xaml/behaviors"
AND
<Hyperlink NavigateUri="{Binding Path=Link}">
<Interactions:Interaction.Behaviors>
<behaviours:HyperlinkOpenBehaviour ConfirmNavigation="True"/>
</Interactions:Interaction.Behaviors>
<Hyperlink.Inlines>
<Run Text="{Binding Path=Link}"/>
</Hyperlink.Inlines>
</Hyperlink>
behaviour code:
using System.Windows;
using System.Windows.Documents;
using System.Windows.Navigation;
using Microsoft.Xaml.Behaviors;
namespace YourNameSpace
{
public class HyperlinkOpenBehaviour : Behavior<Hyperlink>
{
public static readonly DependencyProperty ConfirmNavigationProperty = DependencyProperty.Register(
nameof(ConfirmNavigation), typeof(bool), typeof(HyperlinkOpenBehaviour), new PropertyMetadata(default(bool)));
public bool ConfirmNavigation
{
get { return (bool) GetValue(ConfirmNavigationProperty); }
set { SetValue(ConfirmNavigationProperty, value); }
}
/// <inheritdoc />
protected override void OnAttached()
{
this.AssociatedObject.RequestNavigate += NavigationRequested;
this.AssociatedObject.Unloaded += AssociatedObjectOnUnloaded;
base.OnAttached();
}
private void AssociatedObjectOnUnloaded(object sender, RoutedEventArgs e)
{
this.AssociatedObject.Unloaded -= AssociatedObjectOnUnloaded;
this.AssociatedObject.RequestNavigate -= NavigationRequested;
}
private void NavigationRequested(object sender, RequestNavigateEventArgs e)
{
if (!ConfirmNavigation || MessageBox.Show("Are you sure?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
OpenUrl();
}
e.Handled = true;
}
private void OpenUrl()
{
// Process.Start(new ProcessStartInfo(AssociatedObject.NavigateUri.AbsoluteUri));
MessageBox.Show($"Opening {AssociatedObject.NavigateUri}");
}
/// <inheritdoc />
protected override void OnDetaching()
{
this.AssociatedObject.RequestNavigate -= NavigationRequested;
base.OnDetaching();
}
}
}
Use rowspan
if you want to extend cells down and colspan
to extend across.
ANT_HOME
is not being resolved. Change %ANT_HOME%\bin
in the Path system environment variable to c:\apache-ant\apache-ant-1.8.2\bin
.
In your spring context configuring below would log the request and response soap messsage.
<bean id="loggingFeature" class="org.apache.cxf.feature.LoggingFeature">
<property name="prettyLogging" value="true" />
</bean>
<cxf:bus>
<cxf:features>
<ref bean="loggingFeature" />
</cxf:features>
</cxf:bus>
I remove -XX:+UseStringDeduplication from eclipse.ini . If you run eclipsec.exe you get better descryiption .
According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource
, as per this line:
java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource
I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource
class in it.
This is a better solution, using:
$("table tr:first-child").has('img')
The module needs to be placed in a folder with the same name as the module. In your case:
$home/WindowsPowerShell/Modules/XMLHelpers/
The full path would be:
$home/WindowsPowerShell/Modules/XMLHelpers/XMLHelpers.psm1
You would then be able to do:
import-module XMLHelpers
td[rowspan] {
vertical-align: top;
text-align: left;
}
See: CSS attribute selectors.
To remove from all tables, (add this to the head or external style sheet)
<style type="text/css">
table td{
border:none;
}
</style>
To summarize and complement the existing answers, as of Windows PowerShell v5.1 / PowerShell Core 7.0.0-preview.4:
David Mohundro's answer rightfully points that instead of [bool]
parameters you should use [switch]
parameters in PowerShell, where the presence vs. absence of the switch name (-Unify
specified vs. not specified) implies its value, which makes the original problem go away.
However, on occasion you may still need to pass the switch value explicitly, particularly if you're constructing a command line programmatically:
In PowerShell Core, the original problem (described in Emperor XLII's answer) has been fixed.
That is, to pass $true
explicitly to a [switch]
parameter named -Unify
you can now write:
pwsh -File .\RunScript.ps1 -Unify:$true # !! ":" separates name and value, no space
The following values can be used: $false
, false
, $true
, true
, but note that passing 0
or 1
does not work.
Note how the switch name is separated from the value with :
and there must be no whitespace between the two.
Note: If you declare a [bool]
parameter instead of a [switch]
(which you generally shouldn't), you must use the same syntax; even though -Unify $false
should work, it currently doesn't - see this GitHub issue.
In Windows PowerShell, the original problem persists, and - given that Windows PowerShell is no longer actively developed - is unlikely to get fixed.
The workaround suggested in LarsWA's answer - even though it is based on the official help topic as of this writing - does not work in v5.1
Using -Command
instead of -File
is the only effective workaround:
:: # From cmd.exe
powershell -Command "& .\RunScript.ps1 -Unify:$true"
With -Command
you're effectively passing a piece of PowerShell code, which is then evaluated as usual - and inside PowerShell passing $true
and $false
works (but not true
and false
, as now also accepted with -File
).
Caveats:
Using -Command
can result in additional interpretation of your arguments, such as if they contain $
chars. (with -File
, arguments are literals).
Using -Command
can result in a different exit code.
For details, see this answer and this answer.
I face same issue with sts 3.8.4, so I tried different settings but not luck, I reinstall jdk again n tried but same problem. Finally I downloaded sts 3.8.2 n it runs with out any issue. Using windows 8, 64 bit os. thanks
you just use the :nth-child(num) in css for add the colspan like
<style>
div.table
{
display:table;
width:100%;
}
div.table-row
{
display:table-row;
}
div.table-td
{
display:table-cell;
}
div.table-row:nth-child(1)
{
display:block;
}
</style>
<div class="table>
<div class="table-row">test</div>
<div class="table-row">
<div class="table-td">data1</div>
<div class="table-td">data2</div>
</div>
</div>
This should solve your problem, you should try to run the following below:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
There are multiple ways of doing that you can use either place
or grid
or even the pack
method.
Sample code:
from tkinter import *
root = Tk()
l = Label(root, text="hello" )
l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
# well you can also use side=LEFT inside the pack method of the label widget.
To place a widget to on basis of columns and rows , use the grid method:
but = Button(root, text="hello" )
but.grid(row=0, column=1)
Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix
wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
Create an xml file jax-ws-catalog.xml under META-INF as below
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
prefer="system">
<system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" />
</catalog>
Now package your jar. No more reference to the local directory, it's all packaged and referenced within
I think $PsHome has the information you're after?
PS .> $PsHome C:\Windows\System32\WindowsPowerShell\v1.0 PS .> Get-Help about_automatic_variables TOPIC about_Automatic_Variables ...
After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.
Just Use
hr
{
padding: 0;
border: none;
border-top: 1px solid #CCC;
color: #333;
text-align: center;
font-size: 12px;
vertical-align:middle;
}
hr:after
{
content: "Or";
display: inline-block;
position: relative;
top: -0.7em;
font-size: 1.2em;
padding: 0 0.25em;
background: white;
}
<UserControl.Resources>
<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
</Style.Resources>
</Style>
</UserControl.Resources>
and
<ListBox ItemsSource="{Binding Path=FirstNames}"
ItemContainerStyle="{StaticResource myLBStyle}">
You just override the style of the listboxitem (see the: TargetType is ListBoxItem)
td
height to less than the natural height of its contentSince table cells want to be at least big enough to encase their content, if the content has no apparent height, the cells can be arbitrarily resized.
By resizing the cells, we can control the row height.
One way to do this, is to set the content with an absolute
position within the relative
cell, and set the height
of the cell, and the left
and top
of the content.
table {_x000D_
width: 100%;_x000D_
}_x000D_
td {_x000D_
border: 1px solid #999;_x000D_
}_x000D_
.set-height td {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
height: 3em;_x000D_
}_x000D_
.set-height p {_x000D_
position: absolute;_x000D_
margin: 0;_x000D_
top: 0;_x000D_
}_x000D_
/* table layout fixed */_x000D_
.layout-fixed {_x000D_
table-layout: fixed;_x000D_
}_x000D_
/* td width */_x000D_
.td-width td:first-child {_x000D_
width: 33%;_x000D_
}
_x000D_
<table><tbody>_x000D_
<tr class="set-height">_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
<td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_
</tr>_x000D_
</tbody></table>_x000D_
<h3>With <code>table-layout: fixed</code> applied:</h3>_x000D_
<table class="layout-fixed"><tbody>_x000D_
<tr class="set-height">_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
<td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_
</tr>_x000D_
</tbody></table>_x000D_
<h3>With <code><td> width</code> applied:</h3>_x000D_
<table class="td-width"><tbody>_x000D_
<tr class="set-height">_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
<td>Foo</td></tr><tr><td>Bar</td><td>Baz</td></tr><tr><td>Qux</td>_x000D_
<td>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</td>_x000D_
</tr>_x000D_
</tbody></table>
_x000D_
The table-layout
property
The second table in the snippet above has table-layout: fixed
applied, which causes cells to be given equal width, regardless of their content, within the parent.
According to caniuse.com, there are no significant compatibility issues regarding the use of table-layout
as of Sept 12, 2019.
Or simply apply width
to specific cells as in the third table.
These methods allow the cell containing the effectively sizeless content created by applying position: absolute
to be given some arbitrary girth.
I really should have thought of this from the start; we can manipulate block level table cell content in all the usual ways, and without completely destroying the content's natural size with position: absolute
, we can leave the table to figure out what the width should be.
table {_x000D_
width: 100%;_x000D_
}_x000D_
td {_x000D_
border: 1px solid #999;_x000D_
}_x000D_
table p {_x000D_
margin: 0;_x000D_
}_x000D_
.cap-height p {_x000D_
max-height: 3em;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<table><tbody>_x000D_
<tr class="cap-height">_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
<td>Foo</td>_x000D_
</tr>_x000D_
<tr class="cap-height">_x000D_
<td><p>Bar</p></td>_x000D_
<td>Baz</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Qux</td>_x000D_
<td><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p></td>_x000D_
</tr>_x000D_
</tbody></table>
_x000D_
This will take care of the empty td:
<td style="min-width: 20px;"></td>
It is terrible to install such Python data science packages independently on Windows. Try Anaconda (one installer, 400 more Python packages, py2 & py3 support). Anaconda really helps me a lot!
And please, whatever you do, configure the listings package to use fixed-width font (as in your example; you'll find the option in the documentation). Default setting uses proportional font typeset on a grid, which is, IMHO, incredibly ugly and unreadable, as can be seen from the other answers with pictures. I am personally very irritated when I must read some code typeset in a proportional font.
Try setting fixed-width font with this:
\lstset{basicstyle=\ttfamily}
If you set the border-collapse
style to collapse
on the parent table you should be able to style the tr
:
(styles are inline for demo)
<table style="border-collapse: collapse;">
<tr>
<td>No Border</td>
</tr>
<tr style="border:2px solid #f00;">
<td>Border</td>
</tr>
<tr>
<td>No Border</td>
</tr>
</table>
Output:
It turns out that lstlisting
is able to format code nicely, but requires a lot of tweaking.
Wikibooks has a good example for the parameters you can tweak.
There is very easy solution to show headers at the top of multi columns list box. Just change the property value to "true" for "columnheads" which is false by default.
After that Just mention the data range in property "rowsource" excluding header from the data range and header should be at first top row of data range then it will pick the header automatically and you header will be freezed.
if suppose you have data in range "A1:H100" and header at "A1:H1" which is the first row then your data range should be "A2:H100" which needs to mention in property "rowsource" and "columnheads" perperty value should be true
Regards, Asif Hameed
If you add [hidden]="true" to div, the actual thing that happens is adding a class [hidden] to this element conditionally with display: none
Please check the style of the element in the browser to ensure no other style affect the display property of an element like this:
If you found display of [hidden] class is overridden, you need to add this css code to your style:
[hidden] {
display: none !important;
}
As of Mongo 3.2 the answers to this question are mostly no longer correct. The new $lookup operator added to the aggregation pipeline is essentially identical to a left outer join:
https://docs.mongodb.org/master/reference/operator/aggregation/lookup/#pipe._S_lookup
From the docs:
{
$lookup:
{
from: <collection to join>,
localField: <field from the input documents>,
foreignField: <field from the documents of the "from" collection>,
as: <output array field>
}
}
Of course Mongo is not a relational database, and the devs are being careful to recommend specific use cases for $lookup, but at least as of 3.2 doing join is now possible with MongoDB.
First question: Can I make a Primary Key that is also a Foreign Key?
Yes. In fact for MySQL workbench I've gotten in the habit of only using primary keys for foreign keys. Really cuts down on the random errors received, like the err:150 stated in the question.
# ERROR: Error 1005: Can't create table 'dbimmobili.condoni' (errno: 150)
This does have something to with indexes, or more specifically how MySQL workbench interprets and works with them. It really gets confused if you change a lot in the model (e.g. foreign keys, indexes, col orders) all in the same forward engineering operation, especially if there is already a database on the other end. For example, I don't think automatically created indexes where deleted automatically after deleting a foreign key.
Here is what I did to fix the error your receiving. Note, it seems cumbersome but compared to the amount of time I spent using other methods, it's not.
1. Make all foreign keys primary keys in the lookup table (the 1 in the 1 to many).
In my case this involved changing id as the pk to username in tbl_users, to username AND company in tbl_companies, and to username AND company AND contact in tbl_company_contacts. It's an app for multiple users to enter multiple company contacts, allowing overlapping and hidding of other users contacts.
2. Delete all diagram relationships and all table index that are not primary keys.
This fixes most of the index issues that are really caused by a buggy MySQL workbench.
3. If your doing this from start to finish, drop the schema on the server so mysql workbench doesn't get confused about the existing indexs and lack there off in the model (issue is caused bby index and foreign key relationship, not index alone).
This reduces a lot of the decisions that the DB, server and Mysql workbench have to make a great deal. These decisions about how to forward engineer something are complicated and intelligent, but imperfect.
4. Now, I consider this back to square one (generally after designing to much too quickly without a stepped process). I still have all the tables, but they are clean at this stage. Now you just:
First, forward engineer just to make sure the tables (without relationships) work as expected.
Follow the relationship chain down thru the primary keys, starting at the top most table (i'm my case tbl_users to tbl_companies). After each relationship, always forward engineer to make sure it runs, then save the model and close, then reverse engineer the model to make sure it takes. This allows you to quickly isolate the problems as they arise, in my case left over index used by old deleted foreign keys (happened 2-3 times).
And tadda, back where you needed to be.
Just needed to drill down to the last li.
#navigation li .navigationLevel2 li
Just adding what fixed it for me, where misspelling is the suspect as per this MSDN blog...
When splitting SQL strings over multiple lines, check that that you are comma separating your SQL string from your parameters (and not trying to concatenate them!) and not missing any spaces at the end of each split line. Not rocket science but hope I save someone a headache.
For example:
db.TableName.SqlQuery(
"SELECT Id, Timestamp, User " +
"FROM dbo.TableName " +
"WHERE Timestamp >= @from " +
"AND Timestamp <= @till;" + [USE COMMA NOT CONCATENATE!]
new SqlParameter("from", from),
new SqlParameter("till", till)),
.ToListAsync()
.Result;
Doing the following in a command prompt works for me, also adding to my User environment variables worked fine as well:
set PATH=%PATH%;C:\Program Files\7-Zip\
echo %PATH%
7z
You should see as output (or something similar - as this is on my laptop running Windows 7):
C:\Users\Phillip>set PATH=%PATH%;C:\Program Files\7-Zip\
C:\Users\Phillip>echo %PATH%
C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Wi
ndows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\
WirelessCommon\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\To
ols\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Fil
es (x86)\QuickTime\QTSystem\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Notepad+
+;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files\7-Zip\
C:\Users\Phillip>7z
7-Zip [64] 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
Usage: 7z <command> [<switches>...] <archive_name> [<file_names>...]
[<@listfiles...>]
<Commands>
a: Add files to archive
b: Benchmark
d: Delete files from archive
e: Extract files from archive (without using directory names)
l: List contents of archive
t: Test integrity of archive
u: Update files to archive
x: eXtract files with full paths
<Switches>
-ai[r[-|0]]{@listfile|!wildcard}: Include archives
-ax[r[-|0]]{@listfile|!wildcard}: eXclude archives
-bd: Disable percentage indicator
-i[r[-|0]]{@listfile|!wildcard}: Include filenames
-m{Parameters}: set compression Method
-o{Directory}: set Output directory
-p{Password}: set Password
-r[-|0]: Recurse subdirectories
-scs{UTF-8 | WIN | DOS}: set charset for list files
-sfx[{name}]: Create SFX archive
-si[{name}]: read data from stdin
-slt: show technical information for l (List) command
-so: write data to stdout
-ssc[-]: set sensitive case mode
-ssw: compress shared files
-t{Type}: Set type of archive
-u[-][p#][q#][r#][x#][y#][z#][!newArchiveName]: Update options
-v{Size}[b|k|m|g]: Create volumes
-w[{path}]: assign Work directory. Empty path means a temporary directory
-x[r[-|0]]]{@listfile|!wildcard}: eXclude filenames
-y: assume Yes on all queries
you can use key function of php to get the key name:
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
like here : PHP:key - Manual
In my case I noticed that disabling my internet connection would make it run as fast as with ctrl-f5, so I went to debug->options->symbols and just unchecked all .pdb locations.
Seems like VS was trying to connect to these servers every time a debug session was launched.
Note that disabling Debug->Options->Debugging->General "Enable source support" or "Require source files to exactly match the original version" wouldn't make any difference.
The simplest way to remove inner html elements and return only text would the JQuery .text() function.
Example:
var text = $('<p>A nice house was found in <b>Toronto</b></p>');
alert( text.html() );
//Outputs A nice house was found in <b>Toronto</b>
alert( text.text() );
////Outputs A nice house was found in Toronto
AJB's "Option B" can be made to work by using the base Ubuntu image and setting up nginx on your own. (It didn't work when I used the Nginx image from Docker Hub.)
Here is the Docker file I used:
FROM ubuntu
RUN apt-get update && apt-get install -y nginx
RUN ln -sf /dev/stdout /var/log/nginx/access.log
RUN ln -sf /dev/stderr /var/log/nginx/error.log
RUN rm -rf /etc/nginx/sites-enabled/default
EXPOSE 80 443
COPY conf/mysite.com /etc/nginx/sites-enabled/mysite.com
CMD ["nginx", "-g", "daemon off;"]
My nginx config (aka: conf/mysite.com):
server {
listen 80 default;
server_name mysite.com;
location / {
proxy_pass http://website;
}
}
upstream website {
server website:3000;
}
And finally, how I start my containers:
$ docker run -dP --name website website
$ docker run -dP --name nginx --link website:website nginx
This got me up and running so my nginx pointed the upstream to the second docker container which exposed port 3000.
Just write the "include" command :
import os
def include(filename):
if os.path.exists(filename):
execfile(filename)
include('myfile.py')
@Deleet :
@bfieck remark is correct, for python 2 and 3 compatibility, you need either :
Python 2 and 3: alternative 1
from past.builtins import execfile
execfile('myfile.py')
Python 2 and 3: alternative 2
exec(compile(open('myfile.py').read()))
I wrote this simple function to produce this format: 01:00:03
Seconds are always shown (even if zero). Minutes are shown if greater than zero or if hours or days are required. Hours are shown if greater than zero or if days are required. Days are shown if greater than zero.
function formatSeconds($secs) {
$result = '';
$seconds = intval($secs) % 60;
$minutes = (intval($secs) / 60) % 60;
$hours = (intval($secs) / 3600) % 24;
$days = intval(intval($secs) / (3600*24));
if ($days > 0) {
$result = str_pad($days, 2, '0', STR_PAD_LEFT) . ':';
}
if(($hours > 0) || ($result!="")) {
$result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . ':';
}
if (($minutes > 0) || ($result!="")) {
$result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':';
}
//seconds aways shown
$result .= str_pad($seconds, 2, '0', STR_PAD_LEFT);
return $result;
} //funct
Examples:
echo formatSeconds(15); //15
echo formatSeconds(100); //01:40
echo formatSeconds(10800); //03:00:00 (mins shown even if zero)
echo formatSeconds(10000000); //115:17:46:40
Another way to do this is:
mongo mongodb://mongoDbIPorDomain:port
These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)
a) Part on the developers' website:
Sign in into: https://developer.apple.com/
Member Center
Certificates, Identifiers & Profiles
Certificates>All
Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.
b) XCode part:
After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.
I suggest the following change
let propertyName = {} as any;
You maybe wanted to do the following:
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
os.remove doesn't resolve unix-style patterns. If you are on a unix-like system you can:
os.system('rm '+test)
Else you can:
import glob, os
test = '/path/*'
r = glob.glob(test)
for i in r:
os.remove(i)
As long as the column is not a unique identifier
UPDATE table set columnName = 0 where columnName is null
Then
Alter the table and set the field to non null and specify a default value of 0
=IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3)
This will firstly check if the cell contains a space, if it does it will return the first value from the space, otherwise it will return the cell value.
Edit
Just to add to the above formula, as it stands if there is no value in the cell it would return 0. If you are looking to display a message or something to tell the user it is empty you could use the following:
=IF(IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3)=0, "Empty", IFERROR(LEFT(A3, FIND(" ", A3, 1)), A3))
You can also add images with simple HTML tags:
<p align="center">
<img src="your_relative_path_here" width="350" title="hover text">
<img src="your_relative_path_here_number_2_large_name" width="350" alt="accessibility text">
</p>
You can list all the tags with skopeo
and jq
for json parsing through cli.
skopeo --override-os linux inspect docker://httpd | jq '.RepoTags'
[
"2-alpine",
"2.2-alpine",
"2.2.29",
"2.2.31-alpine",
"2.2.31",
"2.2.32-alpine",
"2.2.32",
"2.2.34-alpine",
"2.2.34",
"2.2",
"2.4-alpine",
"2.4.10",
"2.4.12",
"2.4.16",
"2.4.17",
"2.4.18",
"2.4.20",
"2.4.23-alpine",
"2.4.23",
"2.4.25-alpine",
"2.4.25",
"2.4.27-alpine",
"2.4.27",
"2.4.28-alpine",
"2.4.28",
"2.4.29-alpine",
"2.4.29",
"2.4.32-alpine",
"2.4.32",
"2.4.33-alpine",
"2.4.33",
"2.4.34-alpine",
"2.4.34",
"2.4.35-alpine",
"2.4.35",
"2.4.37-alpine",
"2.4.37",
"2.4.38-alpine",
"2.4.38",
"2.4.39-alpine",
"2.4.39",
"2.4.41-alpine",
"2.4.41",
"2.4.43-alpine",
"2.4.43",
"2.4",
"2",
"alpine",
"latest"
]
For external registries:
skopeo --override-os linux inspect --creds username:password docker://<registry-url>/<repo>/<image> | jq '.RepoTags'
Note: --override-os linux
is only needed if you are not running on a linux host. For example, you'll have better results with it if you are on MacOS.
In my case it was a localgroup which was already existed through a previous install. Removing localgroup (AS_Observers) resolved my issue.
net localgroup AS_Observers /delete
hope this might help someone.
I've got a similar problem I'm currently working on solving. I can't say this will solve your error since there may be issues with other software (which is my case with Eclipse Luna).
Java is using the path given in your PATH variable, which is,
C:\ProgramData\Oracle\Java\javapath
Go to this folder (ProgramData is hidden, so unhide it if necessary) and right click on the java.exe symlink. You'll see in the Target field where it's looking for java.exe. It may be pointing to the java.exe file from your previous jdk1.6.0_45 install. Either paste in new shortcuts here or change the PATH setting as others have mentioned.
I've found that the Java installer doesn't change the javapath or update the system path, at least when going from 1.8 to 1.7. In my case changing the shortcuts only led to a problem with Eclipse on startup.
EDIT:----- After playing with javapath folder shortcuts it turns out you need symlinks, at least for Eclipse. See, Windows how to create directory symlink.
You don't need the /d switch for a file symlink,
mklink java.exe "C:\Program Files\Java\jdk1.8.0_20\bin\java.exe"
mklink javaw.exe "C:\Program Files\Java\jdk1.8.0_20\bin\javaw.exe"
mklink javaws.exe "C:\Program Files\Java\jdk1.8.0_20\bin\javaws.exe"
This now works for me.
Another option that nobody here has mentioned yet is to do a staggered load of the database using a tool like BigDump to work around the limit. It's a simple PHP script that loads a chunk of the database at a time before restarting itself and moving on the the next chunk.
You need the whole python package, with a setup.py
file in it.
A package named foo
would be:
foo # the installable package
+-- foo
¦ +-- __init__.py
¦ +-- bar.py
+-- setup.py
And install from github like:
$ pip install git+ssh://[email protected]/myuser/foo.git
or
$ pip install git+https://github.com/myuser/foo.git@v123
or
$ pip install git+https://github.com/myuser/foo.git@newbranch
More info at https://pip.pypa.io/en/stable/reference/pip_install/#vcs-support
The Scanner class is bases on logic implemented in String next(Pattern)
method. The additional API method like nextDouble()
or nextFloat()
. Provide the pattern inside.
Then class description says:
A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
From the description it can be sad that someone has forgot about char as it is a primitive type for sure.
But the concept of class is to find patterns, a char has no pattern is just next character. And this logic IMHO caused that nextChar has not been implemented.
If you need to read a filed char by char you can used more efficient class.
using JQuery:
myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top, myelement.width(), myelement.height()]
In addition to the accepted answer by @Andreas Mueller, just want to add that as @tangy mentioned above:
StratifiedShuffleSplit most closely resembles train_test_split(stratify = y) with added features of:
SELECT DATEDIFF( now(), '2013-06-20' );
here datediff takes two arguments 'upto-date', 'from-date'
What i have done is, using now() function, i can get no. of days since 20-june-2013 till today.
If you compute modulo a power of two, using bitwise AND is simpler and generally faster than performing division. If b
is a power of two, a % b == a & (b - 1)
.
For example, let's take a value in register EAX, modulo 64.
The simplest way would be AND EAX, 63
, because 63 is 111111 in binary.
The masked, higher digits are not of interest to us. Try it out!
Analogically, instead of using MUL or DIV with powers of two, bit-shifting is the way to go. Beware signed integers, though!
If you would like to use autocomplete all the time without having to worry about hitting Ctrl + Spacebar or your own keyboard shortcut, you can make the following adjustment in the Eclipse preferences to trigger autocomplete simply by typing several different characters:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._
Now any time that you type any of these characters, Eclipse will trigger autocomplete suggestions based on the context.
Try ZZ
to save and close.
Here is a bit more info on using vim with Git
if re.match(regex, content):
blah..
You could also use re.search
depending on how you want it to match.
Just add the following to your html code (withing the <head>
) and you are done.
HTML:
<style>
tr:nth-of-type(odd) {
background-color:#ccc;
}
</style>
Easier and faster than jQuery examples.
Just a little addition to the answer of @dAm2k :
In addition to sudo apt-get remove --purge mysql\*
I've done a sudo apt-get remove --purge mariadb\*
.
I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.
Hope it helps.
As of now you still can't animate rotations with jQuery, but you can with CSS3 animations, then simply add and remove the class with jQuery to make the animation occur.
HTML
<img src="http://puu.sh/csDxF/2246d616d8.png" width="30" height="30"/>
CSS3
img {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
transition-duration:0.4s;
}
.rotate {
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
transition-duration:0.4s;
}
jQuery
$(document).ready(function() {
$("img").mouseenter(function() {
$(this).addClass("rotate");
});
$("img").mouseleave(function() {
$(this).removeClass("rotate");
});
});
Thanks loads for the answers above. I'm adding an answer for a specific use-case...
On a project with two target architectures each with its own build configuration (the main target is an embedded AVR platform; the second target is my local Linux PC for running unit tests) I found it necessary to set Preferences -> C/C++ -> Indexer -> Use active build configuration
as well as to add /usr/include/c++/4.7
, /usr/include
and /usr/include/c++/4.7/x86_64-linux-gnu
to Project Properties -> C/C++ General -> Paths and Symbols
and then to rebuild the index.
I'm dealing with a similar problem currently.
There are two main options that occur to me immediately: (1) user-string checking, or (2) maintaining separate mobile pages using a different URL and having users choose what's better for them.
<link rel="mobile.css" />
instead of the normal style.User strings have identifying information about browser, renderer, operating system, etc. It would be up to you to decide what devices are "touch" versus non-touch. You may be able to find this information available somewhere and map it into your system.
A. If you're allowed to ignore old browsers, you just have to add a single rule to the normal, non-mobile css, namely: EDIT: Erk. After doing some experimentation, I discovered the below rule also disables the ability to follow links in webkit-browsers in addition to just causing aesthetic effects to be disabled - see http://jsfiddle.net/3nkcdeao/
As such, you'll have to be a bit more selective as to how you modify rules for the mobile case than what I show here, but it may be a helpful starting point:
* {
pointer-events: none !important; /* only use !important if you have to */
}
As a sidenote, disabling pointer-events on a parent and then explicitly enabling them on a child currently causes any hover-effects on the parent to become active again if a child-element enters :hover
.
See http://jsfiddle.net/38Lookhp/5/
B. If you're supporting legacy web-renderers, you'll have to do a bit more work along the lines of removing any rules which set special styles during :hover
. To save everyone time, you might just want to build an automated copying + seding command which you run on your standard style sheets to create the mobile versions. That would allow you to just write/update the standard code and scrub away any style-rules which use :hover
for the mobile version of your pages.
Again here, you may be able to just add an extra rule or two to the stylesheets or be forced to do something slightly more complicated using sed or a similar utility. It would probably be easiest to apply :not to your styling rules like div:not(.disruptive):hover {...
wherein you would add class="disruptive"
to elements doing annoying things for mobile users using js or the server language, instead of munging the CSS.
(II) You can actually combine the first two and (if you suspect a user has wandered to the wrong version of a page) you can suggest that they switch into/out of the mobile-type display, or simply have a link somewhere which allows users to flop back and forth. As already-stated, @media queries might also be something to look use in determining what's being used to visit.
(III) If you're up for a jQuery solution once you know what devices are "touch" and which aren't, you might find CSS hover not being ignored on touch-screen devices helpful.
Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.
java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split("@")[0]
datagridview1.Rows[0].HeaderCell.Value = "Your text";
It works.
You state in the comments that the returned JSON is this:
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
You're telling Gson that you have an array of Post
objects:
List<Post> postsList = Arrays.asList(gson.fromJson(reader,
Post[].class));
You don't. The JSON represents exactly one Post
object, and Gson is telling you that.
Change your code to be:
Post post = gson.fromJson(reader, Post.class);
Clustered indexes are stored physically on the table. This means they are the fastest and you can only have one clustered index per table.
Non-clustered indexes are stored separately, and you can have as many as you want.
The best option is to set your clustered index on the most used unique column, usually the PK. You should always have a well selected clustered index in your tables, unless a very compelling reason--can't think of a single one, but hey, it may be out there--for not doing so comes up.
If example Url is http://www.foobar.com/Page1
HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"
HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"
HttpContext.Current.Request.Url.Scheme; //returns "http/https"
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"
As long as you are using CREATE TABLE
, if you are creating the primary key on a single field, you can use:
CREATE TABLE mytable (
field1 TEXT,
field2 INTEGER PRIMARY KEY,
field3 BLOB,
);
With CREATE TABLE
, you can also always use the following approach to create a primary key on one or multiple fields:
CREATE TABLE mytable (
field1 TEXT,
field2 INTEGER,
field3 BLOB,
PRIMARY KEY (field2, field1)
);
Reference: http://www.sqlite.org/lang_createtable.html
This answer does not address table alteration.
Why can't you initialize when you declare?
Which C compiler are you using? Does it support C99?
If it does support C99, you can declare the variable where you need it and initialize it when you declare it.
The only excuse I can think of for not doing that would be because you need to declare it but do an early exit before using it, so the initializer would be wasted. However, I suspect that any such code is not as cleanly organized as it should be and could be written so it was not a problem.
Once you have a JArray you can treat it just like any other Enumerable object, and using linq you can access them, check them, verify them, and select them.
var str = @"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));
If you specify @GET("foobar?a=5")
, then any @Query("b")
must be appended using &
, producing something like foobar?a=5&b=7
.
If you specify @GET("foobar")
, then the first @Query
must be appended using ?
, producing something like foobar?b=7
.
That's how Retrofit works.
When you specify @GET("foobar?")
, Retrofit thinks you already gave some query parameter, and appends more query parameters using &
.
Remove the ?
, and you will get the desired result.
The key is git submodules.
Start reading the Submodules chapter of the Git Community Book or of the Users Manual
Say you have repository PROJECT1, PROJECT2, and MEDIA...
cd /path/to/PROJECT1
git submodule add ssh://path.to.repo/MEDIA
git commit -m "Added Media submodule"
Repeat on the other repo...
Now, the cool thing is, that any time you commit changes to MEDIA, you can do this:
cd /path/to/PROJECT2/MEDIA
git pull
cd ..
git add MEDIA
git commit -m "Upgraded media to version XYZ"
This just recorded the fact that the MEDIA submodule WITHIN PROJECT2 is now at version XYZ.
It gives you 100% control over what version of MEDIA each project uses. git submodules are great, but you need to experiment and learn about them.
With great power comes the great chance to get bitten in the rump.
those are routes you're passing in
<%= Html.ActionLink("Delete", "Delete",
new { id = item.storyId },
new { onclick = "return confirm('Are you sure you wish to delete this article?');" }) %>
The overloaded method you're looking for is this one:
public static MvcHtmlString ActionLink(
this HtmlHelper htmlHelper,
string linkText,
string actionName,
Object routeValues,
Object htmlAttributes
)
If you are running xampp on linux based image, to change root directory open:
/opt/lampp/etc/httpd.conf
Change default document root:
DocumentRoot "/opt/lampp/htdocs" and <Directory "/opt/lampp/htdocs"
to your folder DocumentRoot "/opt/lampp/htdocs/myFolder" and <Directory "/opt/lampp/htdocs/myFolder">
print self.id.__str__()
would work for you, although not that useful for you.
Your __str__
method will be more useful when you say want to print out a grid or struct representation as your program develops.
print self._grid.__str__()
def __str__(self):
"""
Return a string representation of the grid for debugging.
"""
grid_str = ""
for row in range(self._rows):
grid_str += str( self._grid[row] )
grid_str += '\n'
return grid_str
The documentation says:
However, JUnit Jupiter’s
org.junit.jupiter.Assertions
class does not provide anassertThat()
method like the one found in JUnit 4’sorg.junit.Assert
class which accepts a HamcrestMatcher
. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.
Example for Hamcrest:
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class HamcrestAssertionDemo {
@Test
void assertWithHamcrestMatcher() {
SubClass subClass = new SubClass();
assertThat(subClass, instanceOf(BaseClass.class));
}
}
Example for AssertJ:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class AssertJDemo {
@Test
void assertWithAssertJ() {
SubClass subClass = new SubClass();
assertThat(subClass).isInstanceOf(BaseClass.class);
}
}
Note that this assumes you want to test behaviors similar to instanceof
(which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.
root@h1:bin[0]# mount h2:/ /x
root@h1:bin[0]# cp /usr/bin/cat /x/usr/local/bin/
root@h1:bin[0]# umount /x
...
root@h2:~[0]# /usr/local/bin/cat
-bash: /usr/local/bin/cat: Text file busy
root@h2:~[126]#
ubuntu 20.04, 5.4.0-40-generic
nfsd problem, after reboot ok
I had this problem because the page I called ajax post from had EnableViewState="false"
and EnableViewStateMac="false"
but not the page called.
When I put this on both pages everything started to work. I suspected this when I saw MAC address exception.
Assuming you have a form like this:
<form id="myForm" action="foo.php" method="post">
<input type="text" value="" />
<input type="submit" value="submit form" />
</form>
You can attach a onsubmit
-event with jQuery like this:
$('#myForm').submit(function() {
alert('Handler for .submit() called.');
return false;
});
If you return false
the form won't be submitted after the function, if you return true or nothing it will submit as usual.
See the jQuery documentation for more info.
You can accomplish this by playing with the opacity of the image and setting the background color of the image to black. By making the image transparent, it will appear darker.
<div class="image">
<img src="http://www.newyorker.com/online/blogs/photobooth/NASAEarth-01.jpg" alt="" />
</div>
CSS:
.image { position: relative; border: 1px solid black; width: 200px; height: 200px; background: black; }
.image img { max-width: 100%; max-height: 100%; }
.image img:hover { opacity: .5 }
You might need to set the browser-specific opacity too to make this work in other browsers too.
You should try Modelio Free Edition. It support UML2, BPMN, SOA and XMI. It is simple to use and their forum is very active.
Another option is to get a ".pem" (public key) file for that particular server, and install it locally into the heart of your JRE's "cacerts" file (use the keytool helper application), then it will be able to download from that server without complaint, without compromising the entire SSL structure of your running JVM and enabling download from other unknown cert servers...
CSS rules are inherited by default - hence the "cascading" name. To get what you want you need to use !important:
form div
{
font-size: 12px;
font-weight: bold;
}
div.content
{
// any rule you want here, followed by !important
}
var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");
alert(var1);
I prefer the immutable version
foo = {
1:1,
2:2,
3:3
}
removeKeys = [1,2]
def woKeys(dct, keyIter):
return {
k:v
for k,v in dct.items() if k not in keyIter
}
>>> print(woKeys(foo, removeKeys))
{3: 3}
>>> print(foo)
{1: 1, 2: 2, 3: 3}
its better to use the Dependency than to attache it to the class.
public function add_question(Request $request)
{
return Request::all();
}
or if you prefer using input variable use
public function add_question(Request $input)
{
return $input::all();
}
you can now use the global request method provided by laravel
request()
for example to get the first_name of a form input.
request()->first_name
// or
request('first_name')
Class1 is not in the global scope.
See below for a working example:
<?php
function __autoload($class)
{
$parts = explode('\\', $class);
require end($parts) . '.php';
}
use Person\Barnes\David as MyPerson;
$class = new MyPerson\Class1();
Edit (2009-12-14):
Just to clarify, my usage of "use ... as" was to simplify the example.
The alternative was the following:
$class = new Person\Barnes\David\Class1();
or
use Person\Barnes\David\Class1;
// ...
$class = new Class1();
In vanilla javaScript - in ES6
(() => {_x000D_
document.querySelector('.parent').addEventListener('click', event => {_x000D_
alert(event.target.classList.contains('child') ? 'Child element.' : 'Parent element.');_x000D_
});_x000D_
})();
_x000D_
.parent {_x000D_
display: inline-block;_x000D_
padding: 45px;_x000D_
background: lightgreen;_x000D_
}_x000D_
.child {_x000D_
width: 120px;_x000D_
height:60px;_x000D_
background: teal;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
Strangely, the answers above removes the 'duplicates' but what if I want to remove the duplicated value also?? The following should be useful and does not create a new object in memory!
def dictRemoveDuplicates(self):
a=[[1,'somevalue1'],[1,'somevalue2'],[2,'somevalue1'],[3,'somevalue4'],[5,'somevalue5'],[5,'somevalue1'],[5,'somevalue1'],[5,'somevalue8'],[6,'somevalue9'],[6,'somevalue0'],[6,'somevalue1'],[7,'somevalue7']]
print(a)
temp = 0
position = -1
for pageNo, item in a:
position+=1
if pageNo != temp:
temp = pageNo
continue
else:
a[position] = 0
a[position - 1] = 0
a = [x for x in a if x != 0]
print(a)
and the o/p is:
[[1, 'somevalue1'], [1, 'somevalue2'], [2, 'somevalue1'], [3, 'somevalue4'], [5, 'somevalue5'], [5, 'somevalue1'], [5, 'somevalue1'], [5, 'somevalue8'], [6, 'somevalue9'], [6, 'somevalue0'], [6, 'somevalue1'], [7, 'somevalue7']]
[[2, 'somevalue1'], [3, 'somevalue4'], [7, 'somevalue7']]
Using nltk.
from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize("This is a string.")
words_in_each_sentence = word_tokenize(sentences)
You may use TweetTokenizer for parsing casual text with emoticons and such.
There are different ways to achieve this, but I'm not sure which one is the best (I don't even know is there is a best way). I know at least two different ways to do this in a ListView:
1. Set divider to null:
1.1. Programmatically
yourListView.setDivider(null);
1.2. XML
This goes inside your ListView element.
android:divider="@null"
2. Set divider to transparent and set its height to 0 to avoid adding space between listview elements:
2.1. Programmatically:
yourListView.setDivider(new ColorDrawable(android.R.color.transparent));
yourListView.setDividerHeight(0);
2.2. XML
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
Late answer, but I just came on this list today!
CREATE TABLE assignment_20101120 AS SELECT * FROM assignment;
Does the same.
Use:
$ dos2unix file
$ grep -v "^$" file
Or just simply awk:
awk 'NF' file
If you don't have dos2unix, then you can use tools like tr:
tr -d '\r' < "$file" > t ; mv t "$file"
This works well for AIX. I am searching for lines containing JOINED<\t>ACTIVE
voradmin cluster status | grep JOINED$'\t'ACTIVE
vorudb201 1 MEMBER(g) JOINED ACTIVE
*vorucaf01 2 SECONDARY JOINED ACTIVE
I got around this with len()
and a simple if/else
statement.
List elements will come back as an integer when wrapped in len()
(1 for present, 0 for absent)
l = []
print(len(l)) # Prints 0
if len(l) == 0:
print("Element is empty")
else:
print("Element is NOT empty")
Output:
Element is empty
Another way of doing the same but with dplyr
library(dplyr)
subdf <- df %>% filter(numbers <= 3) %>% droplevels()
str(subdf)
Edit:
Also Works ! Thanks to agenis
subdf <- df %>% filter(numbers <= 3) %>% droplevels
levels(subdf$letters)
There seems to be a lot of answers equating socket with the connection between 2 PC's..which I think is absolutely incorrect. A socket has always been the endpoint on 1 PC, that may or may not be connected - surely we've all used listener or UDP sockets* at some point. The important part is that it's addressable and active. Sending a message to 1.1.1.1:1234 is not likely to work, as there is no socket defined for that endpoint.
Sockets are protocol specific - so the implementation of uniqueness that both TCP/IP and UDP/IP uses* (ipaddress:port), is different than eg., IPX (Network, Node, and...ahem, socket - but a different socket than is meant by the general "socket" term. IPX socket numbers are equivalent to IP ports). But, they all offer a unique addressable endpoint.
Since IP has become the dominant protocol, a port (in networking terms) has become synonomous with either a UDP or TCP port number - which is a portion of the socket address.
UDP is connection-less - meaning no virtual circuit between the 2 endpoints is ever created. However, we still refer to UDP sockets as the endpoint. The API functions make it clear that both are just different type of sockets - SOCK_DGRAM
is UDP (just sending a message) and SOCK_STREAM
is TCP (creating a virtual circuit).
Technically, the IP header holds the IP Address, and the protocol on top of IP (UDP or TCP) holds the port number. This makes it possible to have other protocols (eg. ICMP that have no port numbers, but do have IP addressing information).
Another method without having to update your Python code at all, would be to redirect via the console.
Basically, have your Python script print()
as usual, then call the script from the command line and use command line redirection. Like this:
$ python ./myscript.py > output.txt
Your output.txt
file will now contain all output from your Python script.
Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .\myscript.py
)
Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).
Either way works, I like to put that logic in the query so the report has to do less.
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
you can do it on real device by run device in Debug mode
Click Debug->Simulate Location -> add .gpx file for your location during run time
The error happens because of you are trying to map a numeric vector to data
in geom_errorbar
: GVW[1:64,3]
. ggplot
only works with data.frame
.
In general, you shouldn't subset inside ggplot
calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame
and you will be able to plot everything in one call.
Here with a dplyr
solution to summarise the data and compute the standard error beforehand.
library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
summarise(mean = mean(value),se = sd(value) / sqrt(n()))
ggplot(d, aes(x = variable, y = mean, fill = Genotype)) +
geom_bar(position = position_dodge(), stat = "identity",
colour="black", size=.3) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se),
size=.3, width=.2, position=position_dodge(.9)) +
xlab("Time") +
ylab("Weight [g]") +
scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"),
labels = c("Knock-out", "Wild type")) +
ggtitle("Effect of genotype on weight-gain") +
scale_y_continuous(breaks = 0:20*4) +
theme_bw()
A simple non-jQuery solution, albeit with a bit of a hack for IE:
var css = ".lightbox { width: 400px; height: 400px; border: 1px solid #333}";
var htmlDiv = document.createElement('div');
htmlDiv.innerHTML = '<p>foo</p><style>' + css + '</style>';
document.getElementsByTagName('head')[0].appendChild(htmlDiv.childNodes[1]);
It seems IE does not allow setting innerText
, innerHTML
or using appendChild
on style
elements. Here is a bug report which demonstrates this, although I think it identifies the problem incorrectly. The workaround above is from the comments on the bug report and has been tested in IE6 and IE9.
Whether you use this, document.write or a more complex solution will really depend on your situation.
Well, you can create an empty 1-D array using the explicit Array constructor:
a = new Array(9)
To create an array of arrays, I think that you'll have to write a nested loop as Marc described.
Try the format syntax:
print ("{0}. {1} appears {2} times.".format(1, 'b', 3.1415))
Outputs:
1. b appears 3.1415 times.
The print function is called just like any other function, with parenthesis around all its arguments.
Try it
<!- HTML -->
<tr onmouseover="mOvr(this,'#ffa');" onmouseout="mOut(this,'#FFF');">
<script>
function mOvr(src,clrOver) {
if (!src.contains(event.fromElement)) {
src.bgColor = clrOver;
}
}
function mOut(src,clrIn) {
if (!src.contains(event.toElement)) {
src.bgColor = clrIn;
}
}
</script>
Comment by @Niagaradad helped me. I was entering the wrong password the whole time.
Notice the error message
ERROR 1045 (28000): Access denied for user 'ayaz'@'localhost' (using password: YES)
It says, Password: Yes. That means I am sending the password to SQL and that is wrong.
Usually root account doesn't have password if you haven't set one. If you have installed mysql via homebrew then root account won't have a password.
Here is the comment.
so, not exactly the same then. NO means you are not sending a password to MySQL. YES means you are sending a password to MySQL but the incorrect one. Did you specifically set a password for the mysql root user when you installed MySQL? By default there is no password so you can use mysql -u root -p and hit enter.
Create an array with the number of items you want first and then convert the array in to a List.
int[] fakeArray = new int[10];
List<int> list = fakeArray.ToList();
var groupedCustomerList = CustomerList.GroupBy(u => u.GroupID)
.Select(grp =>new { GroupID =grp.Key, CustomerList = grp.ToList()})
.ToList();
In Chrome Browser go to setting , clear browsing history and then reload the page
You can use %in%
data[data$Code %in% selected,]
Code Value
1 A 1
2 B 2
7 A 3
8 A 4
Use $dirty
flag to show the error only after user interacted with the input:
<div>
<input type="email" name="email" ng-model="user.email" required />
<span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>
If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:
<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
<div>
<input type="email" name="email" ng-model="user.email" required />
<span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
Email is required
</span>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
function MyCtrl($scope){
$scope.submit = function(){
// Set the 'submitted' flag to true
$scope.submitted = true;
// Send the form to server
// $http.post ...
}
};
Then, if all that JS inside ng-show
expression looks too much for you, you can abstract it into a separate method:
function MyCtrl($scope){
$scope.submit = function(){
// Set the 'submitted' flag to true
$scope.submitted = true;
// Send the form to server
// $http.post ...
}
$scope.hasError = function(field, validation){
if(validation){
return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
}
return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
};
};
<form ng-submit="submit()" name="form">
<div>
<input type="email" name="email" ng-model="user.email" required />
<span ng-show="hasError('email', 'required')">required</span>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
Use the shell function test
:
foo:
test $(something)
Usage:
$ make foo
test
Makefile:2: recipe for target 'foo' failed
make: *** [foo] Error 1
$ make foo something=x
test x
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
I had similar problem with margin collapse because of parent having position
set to relative. Here are list of commands you can use to disable margin collapsing.
Just try to assign any parent-fix*
class to div.container
element, or any class children-fix*
to div.margin
. Pick the one that fits your needs best.
When
div.absolute
with red background will be positioned at the very top of the page.div.absolute
will be positioned at the same Y coordinate as div.margin
html, body { margin: 0; padding: 0; }_x000D_
_x000D_
.container {_x000D_
width: 100%;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 50px;_x000D_
right: 50px;_x000D_
height: 100px;_x000D_
border: 5px solid #F00;_x000D_
background-color: rgba(255, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
.margin {_x000D_
width: 100%;_x000D_
height: 20px;_x000D_
background-color: #444;_x000D_
margin-top: 50px;_x000D_
color: #FFF;_x000D_
}_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
collapsing from within parent (.container) */_x000D_
.parent-fix1 { padding-top: 1px; }_x000D_
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}_x000D_
.parent-fix3 { overflow: auto;}_x000D_
.parent-fix4 { float: left;}_x000D_
.parent-fix5 { display: inline-block; }_x000D_
.parent-fix6 { position: absolute; }_x000D_
.parent-fix7 { display: flex; }_x000D_
.parent-fix8 { -webkit-margin-collapse: separate; }_x000D_
.parent-fix9:before { content: ' '; display: table; }_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
collapsing from within children (.margin) */_x000D_
.children-fix1 { float: left; }_x000D_
.children-fix2 { display: inline-block; }
_x000D_
<div class="container parent-fix1">_x000D_
<div class="margin children-fix">margin</div>_x000D_
<div class="absolute"></div>_x000D_
</div>
_x000D_
Here is jsFiddle with example you can edit
@David Conrad solution is the fastest I tried using the Normalizer, but it does have a bug. It basically strips characters which are not accents, for example Chinese characters and other letters like æ, are all stripped. The characters that we want to strip are non spacing marks, characters which don't take up extra width in the final string. These zero width characters basically end up combined in some other character. If you can see them isolated as a character, for example like this `, my guess is that it's combined with the space character.
public static String flattenToAscii(String string) {
char[] out = new char[string.length()];
String norm = Normalizer.normalize(string, Normalizer.Form.NFD);
int j = 0;
for (int i = 0, n = norm.length(); i < n; ++i) {
char c = norm.charAt(i);
int type = Character.getType(c);
//Log.d(TAG,""+c);
//by Ricardo, modified the character check for accents, ref: http://stackoverflow.com/a/5697575/689223
if (type != Character.NON_SPACING_MARK){
out[j] = c;
j++;
}
}
//Log.d(TAG,"normalized string:"+norm+"/"+new String(out));
return new String(out);
}
Definitely the HTML5 element is the way to go. There's at least basic support for it in the most recent versions of almost all browsers:
http://caniuse.com/#feat=audio
And it allows to specify what to do when the element is not supported by the browser. For example you could add a link to a file by doing:
<audio controls src="intro.mp3">
<a href="intro.mp3">Introduction to HTML5 (10:12) - MP3 - 3.2MB</a>
</audio>
You can find this examples and more information about the audio element in the following link:
http://hacks.mozilla.org/2012/04/enhanceyourhtml5appwithaudio/
Finally, the good news are that mozilla's April's dev Derby is about this element so that's probably going to provide loads of great examples of how to make the most out of this element:
http://hacks.mozilla.org/2012/04/april-dev-derby-show-us-what-you-can-do-with-html5-audio/
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
Follow these steps with Notepad++
1- Copy the original text
2- In Notepad++, open new file, change Encoding -> pick an encoding you think the original text follows. Try as well the encoding "ANSI" as sometimes Unicode files are read as ANSI by certain programs
3- Paste
4- Then to convert to Unicode by going again over the same menu: Encoding -> "Encode in UTF-8" (Not "Convert to UTF-8") and hopefully it will become readable
The above steps apply for most languages. You just need to guess the original encoding before pasting in notepad++, then convert through the same menu to an alternate Unicode-based encoding to see if things become readable.
Most languages exist in 2 forms of encoding: 1- The old legacy ANSI (ASCII) form, only 8 bits, was used initially by most computers. 8 bits only allowed 256 possibilities, 128 of them where the regular latin and control characters, the final 128 bits were read differently depending on the PC language settings 2- The new Unicode standard (up to 32 bit) give a unique code for each character in all currently known languages and plenty more to come. if a file is unicode it should be understood on any PC with the language's font installed. Note that even UTF-8 goes up to 32 bit and is just as broad as UTF-16 and UTF-32 only it tries to stay 8 bits with latin characters just to save up disk space
window.location
sets the URL of your current window. To open a new window, you need to use window.open
. This should work:
function ToKey(){
var key = document.tokey.key.value.toLowerCase();
if (key == "smk") {
window.open('http://www.smkproduction.eu5.org', '_blank');
} else {
alert("Kodi nuk është valid!");
}
}
I would handle it like so:
$(document).ready(function() {
$('input[type="radio"]').click(function() {
if($(this).attr('id') == 'watch-me') {
$('#show-me').show();
}
else {
$('#show-me').hide();
}
});
});
This is possible with a bit of format conversion.
To extract the private key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -nocerts -nodes | openssl rsa > id_rsa
To convert the private key to a public key:
openssl rsa -in id_rsa -pubout | ssh-keygen -f /dev/stdin -i -m PKCS8
To extract the public key in a format openssh can use:
openssl pkcs12 -in pkcs12.pfx -clcerts -nokeys | openssl x509 -pubkey -noout | ssh-keygen -f /dev/stdin -i -m PKCS8
I don't know about all the lifecycle hooks, but as for destruction, ngOnDestroy
actually get called on Injectable when it's provider is destroyed (for example an Injectable supplied by a component).
From the docs :
Lifecycle hook that is called when a directive, pipe or service is destroyed.
Just in case anyone is interested in destruction check this question:
MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.
From MSDN:
Specifies the maximum length of array or string data allowed in a property.
StringLength is a data annotation that will be used for validation of user input.
From MSDN:
Specifies the minimum and maximum length of characters that are allowed in a data field.
Use [String Length]
[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]
30 is the Max Length
Minimum length = 3
public class MyStringLengthAttribute : StringLengthAttribute
{
public MyStringLengthAttribute(int maximumLength)
: base(maximumLength)
{
}
public override bool IsValid(object value)
{
string val = Convert.ToString(value);
if (val.Length < base.MinimumLength)
base.ErrorMessage = "Minimum length should be 3";
if (val.Length > base.MaximumLength)
base.ErrorMessage = "Maximum length should be 6";
return base.IsValid(value);
}
}
public class MyViewModel
{
[MyStringLength(6, MinimumLength = 3)]
public String MyProperty { get; set; }
}
Your class MyClass
creates a new MyClassToBeTested
, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.
First, you should install "platformio-ide-terminal": Open "Preferences ?," >> Click "+ Install" >> In "Search packages" type "platformio-ide-terminal" >> Click "Install".
And answering exactly the question. If you have previously installed, just use:
ctrl-`
or Option+Command+T (??T)I was getting the same error message but had a different issue. Posting for others that are stuck on same.
I ported the get
, post
, put
, delete
functions to new router file while refactoring, and forgot to edit the paths. Example:
Incorrect:
//server.js
app.use('/blog-posts', blogPostsRouter);
//routers/blogPostsRouter.js
router.get('/blog-posts', (req, res) => {
res.json(BlogPosts.get());
});
Correct:
//server.js
app.use('/blog-posts', blogPostsRouter);
//routers/blogPostsRouter.js
router.get('/', (req, res) => {
res.json(BlogPosts.get());
});
Took a while to spot, as the error had me checking syntax where I might have been wrapping an argument in an object or where I missed the module.exports = router;
When I create a root class, whose methods I defined using the arrow functions. When inheriting and overwriting the original function I noticed the same issue.
class C {
x = () => 1;
};
class CC extends C {
x = (foo) => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
this is solved by defining the method of the parent class without arrow functions
class C {
x() {
return 1;
};
};
class CC extends C {
x = foo => super.x() + foo;
};
let add = new CC;
console.log(add.x(4));
Could not get this to work until I put Authorization in single quotes:
axios.get(URL, { headers: { 'Authorization': AuthStr } })
Try something like this:
awk -vc=1 'NR%1000000==0{++c}{print $0 > c".txt"}' Datafile.txt
for filename in *.txt; do mv "$filename" "Prefix_$filename"; done;
Without a GROUP BY clause, any summation will roll all rows up into a single row, so your query will indeed not work. If you grouped by, say, name, and ordered by sum(c_counts+f_counts), then you might get some useful results. But you would have to group by something.
I also face the similar Issue. Nothing programmer has to do to resolve this error. I informed to my oracle DBA team. They kill the session and worked like a charm.
The native option is missing so I'll add it for the next guy/gall that looks for it.
Starting on Django 1.7.x there is a built-in DjangoJSONEncoder
that you can get it from django.core.serializers.json
.
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.forms.models import model_to_dict
model_instance = YourModel.object.first()
model_dict = model_to_dict(model_instance)
json.dumps(model_dict, cls=DjangoJSONEncoder)
Presto!
This is actually redundant except in cases where you want to override the defaults. All of these settings are implied defaults.
You can verify that by checking your effective POM using this command
mvn help:effective-pom
<finalName>name</finalName>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
For example, if i want to point to a different test resource path or resource path you should use this otherwise you don't.
<resources>
<resource>
<directory>/home/josh/desktop/app_resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>/home/josh/desktop/test_resources</directory>
</testResource>
</testResources>
Correct way (if you are not trying to reset the value of the hidden_field input) is:
f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form
Where :method
is the method that when called on the object results in the value you want
So following the example above:
= simple_form_for @movie do |f|
= f.hidden :title, "some value"
= f.button :submit
The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:
= simple_form_for @movie do |f|
= f.hidden :title, :value => params[:movie][:title]
= f.button :submit
Again only use my answer is you do not want to reset the value submitted by the user.
I hope this makes sense.
It's simple to convert the Unix timestamp into the desired format. Lets suppose _ts is the Unix timestamp in long
let date = NSDate(timeIntervalSince1970: _ts)
let dayTimePeriodFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "MMM dd YYYY hh:mm a"
let dateString = dayTimePeriodFormatter.stringFromDate(date)
print( " _ts value is \(_ts)")
print( " _ts value is \(dateString)")
To do this in Swift3 following is the code:
let labelSizeWithFixedWith = CGSize(width: 300, height: CGFloat.greatestFiniteMagnitude)
let exactLabelsize = self.label.sizeThatFits(labelSizeWithFixedWith)
self.label.frame = CGRect(origin: CGPoint(x: 20, y: 20), size: exactLabelsize)
Use the retainAll()
method of Set
:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
If you want to preserve the sets, create a new set to hold the intersection:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);
The javadoc of retainAll()
says it's exactly what you want:
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
Well, I figured out the problem.
Basically Go starting path for import is $HOME/go/src
So I just needed to add myapp
in front of the package names, that is, the import should be:
import (
"log"
"net/http"
"myapp/common"
"myapp/routers"
)
If your items in the array are not primitive you can use spread operator to do that.
this.plansCopy = this.plans.map(obj => ({...obj}));
Complete answer : https://stackoverflow.com/a/47776875/5775048
In my case I was trying to install Flask. I wanted to run pip install Flask command. But when I open command prompt it I goes to C:\Users[user]>. If you give here it will say pip is not recognized. I did below steps
On your desktop right click Computer and select Properties
Select Advanced Systems Settings
In popup which you see select Advanced tab and then click Environment Variables
In popup double click PATH and from popup copy variable value for variable name PATH and paste the variable value in notepad or so and look for an entry for Python.
In my case it was C:\Users\[user]\AppData\Local\Programs\Python\Python36-32
Now in my command prompt i moved to above location and gave pip install Flask
JavaScript (ECMAScript edition 3) has an implements
reserved word saved up for future use. I think this is intended exactly for this purpose, however, in a rush to get the specification out the door they didn't have time to define what to do with it, so, at the present time, browsers don't do anything besides let it sit there and occasionally complain if you try to use it for something.
It is possible and indeed easy enough to create your own Object.implement(Interface)
method with logic that baulks whenever a particular set of properties/functions are not implemented in a given object.
I wrote an article on object-orientation where use my own notation as follows:
// Create a 'Dog' class that inherits from 'Animal'
// and implements the 'Mammal' interface
var Dog = Object.extend(Animal, {
constructor: function(name) {
Dog.superClass.call(this, name);
},
bark: function() {
alert('woof');
}
}).implement(Mammal);
There are many ways to skin this particular cat, but this is the logic I used for my own Interface implementation. I find I prefer this approach, and it is easy to read and use (as you can see above). It does mean adding an 'implement' method to Function.prototype
which some people may have a problem with, but I find it works beautifully.
Function.prototype.implement = function() {
// Loop through each interface passed in and then check
// that its members are implemented in the context object (this).
for(var i = 0; i < arguments.length; i++) {
// .. Check member's logic ..
}
// Remember to return the class being tested
return this;
}
You can prefix the function declaration with extern “C” keyword, e.g.
extern “C” int Mycppfunction()
{
// Code goes here
return 0;
}
For more examples you can search more on Google about “extern” keyword. You need to do few more things, but it's not difficult you'll get lots of examples from Google.
Environment variables are accessed through os.environ
import os
print(os.environ['HOME'])
Or you can see a list of all the environment variables using:
os.environ
As sometimes you might need to see a complete list!
# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
Python default installation on Windows is C:\Python
. If you want to find out while running python you can do:
import sys
print(sys.prefix)
In PostgreSQL 9.4 to create to file CSV with the header in Ubuntu:
COPY (SELECT * FROM tbl) TO '/home/user/Desktop/result_sql.csv' WITH CSV HEADER;
Note: The folder must be writable.
WinSQL: I wanted to return all records for last month:
where DATE01 between dateadd(month,-1,dateadd(day,1,dateadd(day,-day(today()),today()))) and dateadd(day,-day(today()),today())
This does the same thing:
where month(DATE01) = month(dateadd(month,-1,today())) and year(DATE01) = year(dateadd(month,-1,today()))
Ok, I solved it. Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.
@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
//Content goes here
}
Yes, it's simple. Just add the DateTimeFormat annotation.
is it possible to export without looping through all records
For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application
object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data
Option Explicit
Sub AccImport()
Dim acc As New Access.Application
acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
acc.DoCmd.TransferSpreadsheet _
TransferType:=acImport, _
SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
TableName:="tblExcelImport", _
Filename:=Application.ActiveWorkbook.FullName, _
HasFieldNames:=True, _
Range:="Folio_Data_original$A1:B10"
acc.CloseCurrentDatabase
acc.Quit
Set acc = Nothing
End Sub
I don't know of any way to do this with grep, but it is possible to use awk to achieve the same result:
awk '/blah/ {getline;print}' < logfile
Bash documentation says that every time $RANDOM
is referenced, a random number between 0 and 32767 is returned. If we sum two consecutive references, we get values from 0 to 65534, which covers the desired range of 63001 possibilities for a random number between 2000 and 65000.
To adjust it to the exact range, we use the sum modulo 63001, which will give us a value from 0 to 63000. This in turn just needs an increment by 2000 to provide the desired random number, between 2000 and 65000. This can be summarized as follows:
port=$((((RANDOM + RANDOM) % 63001) + 2000))
Testing
# Generate random numbers and print the lowest and greatest found
test-random-max-min() {
max=2000
min=65000
for i in {1..10000}; do
port=$((((RANDOM + RANDOM) % 63001) + 2000))
echo -en "\r$port"
[[ "$port" -gt "$max" ]] && max="$port"
[[ "$port" -lt "$min" ]] && min="$port"
done
echo -e "\rMax: $max, min: $min"
}
# Sample output
# Max: 64990, min: 2002
# Max: 65000, min: 2004
# Max: 64970, min: 2000
Correctness of the calculation
Here is a full, brute-force test for the correctness of the calculation. This program just tries to generate all 63001 different possibilities randomly, using the calculation under test. The --jobs
parameter should make it run faster, but it's not deterministic (total of possibilities generated may be lower than 63001).
test-all() {
start=$(date +%s)
find_start=$(date +%s)
total=0; ports=(); i=0
rm -f ports/ports.* ports.*
mkdir -p ports
while [[ "$total" -lt "$2" && "$all_found" != "yes" ]]; do
port=$((((RANDOM + RANDOM) % 63001) + 2000)); i=$((i+1))
if [[ -z "${ports[port]}" ]]; then
ports["$port"]="$port"
total=$((total + 1))
if [[ $((total % 1000)) == 0 ]]; then
echo -en "Elapsed time: $(($(date +%s) - find_start))s \t"
echo -e "Found: $port \t\t Total: $total\tIteration: $i"
find_start=$(date +%s)
fi
fi
done
all_found="yes"
echo "Job $1 finished after $i iterations in $(($(date +%s) - start))s."
out="ports.$1.txt"
[[ "$1" != "0" ]] && out="ports/$out"
echo "${ports[@]}" > "$out"
}
say-total() {
generated_ports=$(cat "$@" | tr ' ' '\n' | \sed -E s/'^([0-9]{4})$'/'0\1'/)
echo "Total generated: $(echo "$generated_ports" | sort | uniq | wc -l)."
}
total-single() { say-total "ports.0.txt"; }
total-jobs() { say-total "ports/"*; }
all_found="no"
[[ "$1" != "--jobs" ]] && test-all 0 63001 && total-single && exit
for i in {1..1000}; do test-all "$i" 40000 & sleep 1; done && wait && total-jobs
For determining how many iterations are needed to get a given probability p/q
of all 63001 possibilities having been generated, I believe we can use the expression below. For example, here is the calculation for a probability greater than 1/2, and here for greater than 9/10.
You simply need to specify on which tables to apply the DELETE
.
Delete only the deadline
rows:
DELETE `deadline` FROM `deadline` LEFT JOIN `job` ....
Delete the deadline
and job
rows:
DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` ....
Delete only the job
rows:
DELETE `job` FROM `deadline` LEFT JOIN `job` ....
r := strings(byteData)
This also works to turn []byte
into io.Reader
I'm guessing you mean ignoring case when searching in a string?
I don't know any, but you could try to convert the string to search into either to lower or to upper case, then search.
// s is the String to search into, and seq the sequence you are searching for.
bool doesContain = s.toLowerCase().contains(seq);
Edit: As Ryan Schipper suggested, you can also (and probably would be better off) do seq.toLowerCase(), depending on your situation.
Goto View -> Show Symbol -> Show All Characters. Uncheck it. There you go.!!
Project -> Clean
can at least sometimes be sufficient to resolve the matter.
Gradle can work with the 18.0.+ notation, it however now depends on the new support repository which is now bundled with the SDK.
Open the SDK manager and immediately under Extras the first option is "Android Support Repository" and install it
1) Install Git for Windows from here: http://git-scm.com/download/win
2) Note: During installation, Make sure "Use Git and optional Unix tools from the windows command prompt" is selected
3) restart the Android Studio and try again
4) Go to File-> New -> Project from version control -> Git
"\t"
not '\t'
, php doesnt escape in single quotes
In AAA style using the explicitly typed initializer idiom:
#include <chrono>
#include <iostream>
int main(){
auto start = std::chrono::high_resolution_clock::now();
// Code to time here...
auto end = std::chrono::high_resolution_clock::now();
auto dur = end - start;
auto i_millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
std::cout << i_millis.count() << '\n';
std::cout << f_secs.count() << '\n';
}
The bare metal thing, you probably don't need to use it, you probably can use a LongRunning
task and take the benefits from the TPL - Task Parallel Library, included in .NET Framework 4 (february, 2002) and above (also .NET Core).
Abstraction above the Threads. It uses the thread pool (unless you specify the task as a LongRunning
operation, if so, a new thread is created under the hood for you).
As the name suggests: a pool of threads. Is the .NET framework handling a limited number of threads for you. Why? Because opening 100 threads to execute expensive CPU operations on a Processor with just 8 cores definitely is not a good idea. The framework will maintain this pool for you, reusing the threads (not creating/killing them at each operation), and executing some of them in parallel, in a way that your CPU will not burn.
In resume: always use tasks.
Task is an abstraction, so it is a lot easier to use. I advise you to always try to use tasks and if you face some problem that makes you need to handle a thread by yourself (probably 1% of the time) then use threads.
LongRunning
tasks (or threads if you need to). Because using tasks would lead you to a thread pool with a few threads busy and a lot of another tasks waiting for its turn to take the pool. Use grep and regular expressions, for example if you want 4 minutes interval of logs:
grep "31/Mar/2002:19:3[1-5]" logfile
will return all logs lines between 19:31 and 19:35 on 31/Mar/2002. Supposing you need the last 5 days starting from today 27/Sep/2011 you may use the following:
grep "2[3-7]/Sep/2011" logfile
Public Class Form1
Private animatedimage As New Bitmap("C:\MyData\Search.gif")
Private currentlyanimating As Boolean = False
Private Sub OnFrameChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
Me.Invalidate()
End Sub
Private Sub AnimateImage()
If currentlyanimating = True Then
ImageAnimator.Animate(animatedimage, AddressOf Me.OnFrameChanged)
currentlyanimating = False
End If
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
AnimateImage()
ImageAnimator.UpdateFrames(animatedimage)
e.Graphics.DrawImage(animatedimage, New Point((Me.Width / 4) + 40, (Me.Height / 4) + 40))
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
BtnStop.Enabled = False
End Sub
Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click
currentlyanimating = False
ImageAnimator.StopAnimate(animatedimage, AddressOf Me.OnFrameChanged)
BtnStart.Enabled = True
BtnStop.Enabled = False
End Sub
Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click
currentlyanimating = True
AnimateImage()
BtnStart.Enabled = False
BtnStop.Enabled = True
End Sub
End Class
Just one more point in favor of the foo == NULL
practice:
If foo
is, say, an int *
or a bool *
, then the if (foo)
check can accidentally be interpreted by a reader as testing the value of the pointee, i.e. as if (*foo)
. The NULL
comparison here is a reminder that we're talking about a pointer.
But I suppose a good naming convention makes this argument moot.
Android Reverse Engineering is possible . Follow these steps to get .java file from apk file.
Step1 . Using dex2jar
dex2jar sampleApp.apk
Step2 . Decompiling .jar using JD-GUI
try this
make trait
import org.apache.spark.sql.SparkSession
trait SparkSessionWrapper {
lazy val spark:SparkSession = {
SparkSession
.builder()
.getOrCreate()
}
}
extends it
object Preprocess extends SparkSessionWrapper {
Quote from the Spring reference doc:
Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there...
Your servlet is called spring-dispatcher
, so it looks for /WEB-INF/spring-dispatcher-servlet.xml
. You need to have this servlet configuration, and define web related beans in there (like controllers, view resolvers, etc). See the linked documentation for clarification on the relation of servlet contexts to the global application context (which is the app-config.xml
in your case).
One more thing, if you don't like the naming convention of the servlet config xml, you can specify your config explicitly:
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
I had to figure out how to do this for 3 columns. I wanted to round the corners of the divs and couldn't get the spacing to work. I used margins. In my case I figured for 90% of the screen to be filled in by the divs and 10% for margins:
html:
<div class="row">
<div id="orange" class="col-md-4">
<h1>Orange Div</h1>
</div>
<div id="green" class="col-md-4">
<h1>Green Div</h1>
</div>
<div id="aqua" class="col-md-4">
<h1>Aqua Div</h1>
</div>
</div>
and CSS:
#orange {
background-color:orange;
border-radius: 30px;
padding: 20px;
margin: 2.5% 2.5% 0 2.5%;
width:30%;
}
#green {
background-color:green;
border-radius: 30px;
padding: 20px;
margin: 2.5% 0 0 0;
width:30%;
}
#aqua {
background-color:#39F;
border-radius: 30px;
padding: 20px;
margin: 2.5% 2.5% 0 2.5%;
width: 30%;
}
To make it resize correctly for mobile devices, I had the CSS change the width from 30% to width:92.5%;
under @media (max-width:1023px)
I had to insert date at the beginning of the lines of a log file and it's done like below:
DATE=$(date +"%Y-%m-%d")
awk '{ print "'"$DATE"'", $0; }' /path_to_log_file/log_file.log
It can be redirect to another file to save
Try this:
-- http://lua-users.org/wiki/FileInputOutput
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
using System.Linq;
string s = string.Join(";", myDict.Select(x => x.Key + "=" + x.Value).ToArray());
(And if you're using .NET 4, or newer, then you can omit the final ToArray
call.)
In Angular 2 there are three places you can "provide" services:
"The bootstrap provider option is intended for configuring and overriding Angular's own preregistered services, such as its routing support." -- reference
If you only want one instance of NameService across your entire app (i.e., Singleton), then include it in the providers
array of your root component:
@Component({
providers: [NameService],
...
)}
export class AppComponent { ... }
If you would rather have one instance per component, use the providers
array in the component's configuration object instead:
@Component({
providers: [NameService],
...
)}
export class SomeOtherComponentOrDirective { ... }
See the Hierarchical Injectors doc for more info.
You can also try the fetch
function and the no-cors
mode. I sometimes find it easier to configure it than Angular's built-in http module. You can right-click requests in the Chrome Dev tools network tab and copy them in the fetch syntax, which is great.
import { from } from 'rxjs';
// ...
result = from( // wrap the fetch in a from if you need an rxjs Observable
fetch(
this.baseurl,
{
body: JSON.stringify(data)
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
mode: 'no-cors'
}
)
);
This is one of the reasons why languages like "Go" do not have assertions. They are used to handle cases that you probably didn't think about, all too often. You should only assert the impossible, not simply the unlikely. Doing the latter is what gives assertions a bad reputation. Every time you type assert(
, walk away for ten minutes and really think about it.
In your particularly disturbing case, it is both conceivable and appalling that such an assertion would be bogus under rare but possible circumstances. Hence, handle it in your app, if only to say "This software was not designed to handle the scenario that you presented".
Asserting that your great, great, great grandfather being your father as impossible is a reasonable thing to do.
If I was working for a testing company that was hired to test your software, of course I would have presented that scenario. Why? Every juvenile yet intelligent 'user' is going to do the exact same thing and relish in the resulting 'bug report'.
you can do it like this:
<script>
function SomeDeleteRowFunction(o) {
//no clue what to put here?
var p=o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
</script>
<table>
<tr>
<td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
</tr>
<tr>
<td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
</tr>
<tr>
<td><input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this)"></td>
</tr>
</table>
CsvHelper library is very popular in the Nuget.You worth it,man! https://github.com/JoshClose/CsvHelper/wiki/Basics
Using CsvHelper is really easy. It's default settings are setup for the most common scenarios.
Here is a little setup data.
Actors.csv:
Id,FirstName,LastName
1,Arnold,Schwarzenegger
2,Matt,Damon
3,Christian,Bale
Actor.cs (custom class object that represents an actor):
public class Actor
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Reading the CSV file using CsvReader:
var csv = new CsvReader( new StreamReader( "Actors.csv" ) );
var actorsList = csv.GetRecords();
Writing to a CSV file.
using (var csv = new CsvWriter( new StreamWriter( "Actors.csv" ) ))
{
csv.WriteRecords( actorsList );
}
I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.
An extended answer for remote IP db connections:
Step 1: Link servers
EXEC sp_addlinkedserver @server='SRV_NAME',
@srvproduct=N'',
@provider=N'SQLNCLI',
@datasrc=N'aaa.bbb.ccc.ddd';
EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'
...where SRV_NAME
is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd
is the ip address of the remote server hosting your SQLserver DB.
Step 2: Run your queries For instance:
SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table
...and that's it!
Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin
Use "/select,c:\file.txt"
Notice there should be a comma after /select instead of space..
I had this noted from somewhere:
adding text-transform to input to remove it
input.button {
text-indent:-9999px;
text-transform:capitalize;
}
Here is how to kill one or more process from a .bat file.
Step 1. Open a preferred text editor and create a new file.
step 2. To kill one process use the 'taskkill' command, with the '/im' parameter that specifies the image name of the process to be terminated. Example:
taskkill /im examplename.exe
To 'force' kill a process use the '/f' parameter which specifies that processes be forcefully terminated. Example:
taskkill /f /im somecorporateprocess.exe
To kill more than one process you rinse and repeat the first part of step 2. Example:
taskkill /im examplename.exe
taskkill /im examplename1.exe
taskkill /im examplename2.exe
or
taskkill /f /im examplename.exe
taskkill /f /im examplename1.exe
taskkill /f /im examplename2.exe
step 3. Save your file to desired location with the .bat extension.
step 4. click newly created bat file to run it.
if you are having a problem as describe in this post:
asp.net mvc debugger throwing SEHException
then the solution is:
if you have any application from Trusteer (like rapport or anything ) just uninstall and reboot your system, it'll work fine ... found this solution here:
http://forums.asp.net/t/1704958.aspx/8/10?Re+SEHException+thrown+when+I+run+the+application
$ENV{FOO}
for usage, where FOO
is being picked up from the environment variable. otherwise use as ${FOO}
, where FOO
is some other variable. For setting, SET(FOO "foo")
would be used in CMake.
You could use the ones on CodePlex or http://www.enterprisedt.com/general/press/20060818.html
It sounds like you need to make use of advanced where clauses.
Given that search in field1
and field2
is constant we will leave them as is, but we are going to adjust your search in datefield
a little.
Try this:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(function ($query) {
$query->where('datefield', '<', $date)
->orWhereNull('datefield');
}
);
If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql()
to the end of your eloquent query to generate the SQL.
status 0 appear when an ajax call was cancelled before getting the response by refreshing the page or requesting a URL that is unreachable.
this status is not documented but exist over ajax and makeRequest call's from gadget.io.
The answer was surprisingly simple. I had to add a Content-Type
header in the POST
request with a value of application/json
. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON)
annotation)!
If you have previously run mvn install on project B it will have been installed to your local repository, so when you build package A Maven can resolve the dependency. So as long as you install project B each time you change it your builds for project A will be up to date.
You can define a multi-module project with an aggregator pom to build a set of projects.
It's also worthwhile mentioning m2eclipse, it integrates Maven into Eclipse and allows you to (optionally) resolve dependencies from the workspace. So if you are hacking away on multiple projects, the workspace content will be used for compilation. Once you are happy with your changes, run mvn install (on each project in turn, or using an aggregator) to put them in your local repository.
For installation in Windows : Download and extract to any directory (lets say c drive)
Then double click on the extracted ngrok.exe
file and you'll be able to see the command prompt
.
And just type ngrok http 4040 // here I am exposing [port 4040]
Lines 1,2,3,4 will call the default constructor. They are different in the essence as 1,2 are dynamically created object and 3,4 are statically created objects.
In Line 7, you create an object inside the argument call. So its an error.
And Lines 5 and 6 are invitation for memory leak.
The question is: how to select the last column of a dataframe ? Appart @piRSquared, none answer the question.
the simplest way to get a dataframe with the last column is:
df.iloc[ :, -1:]
According to the documentation:
$validator = Validator::make($request->all(), [
'file' => 'max:500000',
]);
The value is in kilobytes. I.e. max:10240
= max 10 MB.
Full Coding Structure
postgresql function
CREATE OR REPLACE FUNCTION admin.usp_itemdisplayid_byitemhead_select(
item_head_list int[])
RETURNS TABLE(item_display_id integer)
LANGUAGE 'sql'
COST 100
VOLATILE
ROWS 1000
AS $BODY$
SELECT vii.item_display_id from admin.view_item_information as vii
where vii.item_head_id = ANY(item_head_list);
$BODY$;
Model
public class CampaignCreator
{
public int item_display_id { get; set; }
public List<int> pitem_head_id { get; set; }
}
.NET CORE function
DynamicParameters _parameter = new DynamicParameters();
_parameter.Add("@item_head_list",obj.pitem_head_id);
string sql = "select * from admin.usp_itemdisplayid_byitemhead_select(@item_head_list)";
response.data = await _connection.QueryAsync<CampaignCreator>(sql, _parameter);
min_element
and max_element
return iterators, not values. So you need *min_element...
and *max_element...
.
Another trick is to use 2 popup windows instead of one. The 1st popup window will simply be a dummy view with translucent background which provides the dim effect. The 2nd popup window is your intended popup window.
Sequence while creating pop up windows: Show the dummy pop up window 1st and then the intended popup window.
Sequence while destroying: Dismiss the intended pop up window and then the dummy pop up window.
The best way to link these two is to add an OnDismissListener and override the onDismiss()
method of the intended to dimiss the dummy popup window from their.
Code for the dummy popup window:
fadepopup.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fadePopup"
android:background="#AA000000">
</LinearLayout>
Show fade popup to dim the background
private PopupWindow dimBackground() {
LayoutInflater inflater = (LayoutInflater) EPGGRIDActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.fadepopup,
(ViewGroup) findViewById(R.id.fadePopup));
PopupWindow fadePopup = new PopupWindow(layout, windowWidth, windowHeight, false);
fadePopup.showAtLocation(layout, Gravity.NO_GRAVITY, 0, 0);
return fadePopup;
}
Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.
There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.
PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.
There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.
You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.
Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!
At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.
In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!
Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?>
on your site and look for the Server API
entry. This could say something like CGI/FastCGI
or Apache 2.0 Handler
.
If you also look at the command-line version of PHP -- thread safety does not matter.
Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!
Here's a little hack that I did.
<div id="element"><!--element that I want an one-sided inset shadow from the bottom--></div>
<div class="one_side_shadow"></div>
1. Create a <div class="one_side_shadow"></div>
right below the element that I want to create the one-side box shadow (in this case I want a one-sided inset shadow for id="element"
coming from the bottom)
2. Then I created a regular box-shadow
using a negative vertical offset to push the shadow upwards to one-side.
`box-shadow: 0 -8px 20px 2px #DEDEE3;`
Mac Users
if you only want the last line deleted output without changing the file itself do
sed -e '$ d' foo.txt
if you want to delete the last line of the input file itself do
sed -i '' -e '$ d' foo.txt
You can also install Fiddler (http://www.fiddler2.com/fiddler2/) which is very easy to install (easier than Apache for example).
After launching it, it will register itself as system proxy. Then open the "Rules" menu, and choose "Customize Rules..." to open a JScript file which allow you to customize requests.
To add a custom header, just add a line in the OnBeforeRequest
function:
oSession.oRequest.headers.Add("MyHeader", "MyValue");
For the equivalent of NVL() and ISNULL() use:
IFNULL(column, altValue)
column
: The column you are evaluating.
altValue
: The value you want to return if 'column' is null.
Example:
SELECT IFNULL(middle_name, 'N/A') FROM person;
*Note: The COALESCE() function works the same as it does for other databases.
Sources:
You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use
ping -n 11 127.0.0.1 > nul
This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)
If your string contains non-ASCII characters - it's better to do it this way:
s.toUtf8().data()
(or s->toUtf8().data()
)
On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.
If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.
<button id="cmdAction"
runat="server" onserverclick="cmdAction_Click()"
class="Button Styles"
title="Does something on the server"
<!-- for databound controls -->
CommandName="cmdname">
CommandArgument="args..."
>
<!-- content -->
<span class="ui-icon ..."></span>
<span class="push">Click Me</span>
</button>
On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.
protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}
There are other solutions as in using custom controls, etc. Also note that I am using this live on projects in VS2K8.
Hoping this helps. Enjoy!
I also faced this same issue while working in my development environment, the problem was that I left host: localhost
commented out in the config/database.yml
file.
So my application could not connect to the PostgreSQL database, simply uncommenting it solved the issue.
development:
<<: *default
database: database_name
username: database_username
password: database_password
host: localhost
That's all.
I hope this helps
Yes, the method above is so great. And I tried some of them. At last, I found a method like this:
from threading import Timer
def sync():
do something...
sync_timer = Timer(self.interval, sync, ())
sync_timer.start()
Just like Recursive.
Ok, I hope this method can meet your requirement. :)
Mod-rewrite based solution :
Using the following code in htaccess automatically forwards all http requests to https.
RewriteEngine on
RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
This will redirect your non-www and www http requests to www version of https.
Another solution (Apache 2.4*)
RewriteEngine on
RewriteCond %{REQUEST_SCHEME}::%{HTTP_HOST} ^http::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
This doesn't work on lower versions of apache as %{REQUEST_SCHEME} variable was added to mod-rewrite since 2.4.
You can check out libvideo. It's much more up-to-date than YoutubeExtractor, and is fast and clean to use.
According to the tkinterbook the code to clear a text element should be:
text.delete(1.0,END)
This worked for me. source
It's different from clearing an entry element, which is done like this:
entry.delete(0,END) #note the 0 instead of 1.0
You only need to do one thing. Run session_object.clear()
and then save the new object. This will clear the session (as aptly named) and remove the offending duplicate object from your session.
There are some good answers on here, so I will just add some process improvements. A better way of determining if the folder exists (does not use FileSystemObjects, which not all computers are allowed to use):
Function FolderExists(FolderPath As String) As Boolean
FolderExists = True
On Error Resume Next
ChDir FolderPath
If Err <> 0 Then FolderExists = False
On Error GoTo 0
End Function
Likewise,
Function FileExists(FileName As String) As Boolean
If Dir(FileName) <> "" Then FileExists = True Else FileExists = False
EndFunction
For future reference and for simplicity sake for the lazy people out there that don't want much explanations but just run things and make it work asap:
1) sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
2) sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
3) sudo yum install -y apache-maven
4) mvn --version
Hope you enjoyed this copy & paste session.
Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".
Go to the "Network & Security" -> Security Group settings in the left hand navigation
Find the Security Group that your instance is apart of Click on Inbound Rules Use the drop down and add HTTP (port 80) Click Apply and enjoy
Yes, you can actually with CSS 2D Transforms. This is supported in almost all modern browsers, including IE9+. Here's an example.
HTML
<p>I feel like <span class="stretch">stretching</span>.</p>
CSS
span.stretch {
display:inline-block;
-webkit-transform:scale(2,1); /* Safari and Chrome */
-moz-transform:scale(2,1); /* Firefox */
-ms-transform:scale(2,1); /* IE 9 */
-o-transform:scale(2,1); /* Opera */
transform:scale(2,1); /* W3C */
}
TIP: You may need to add margin to your stretched text to prevent text collisions.
function addValueInObject(value, object, key) {
var addMoreOptions = eval('{"' + key + '":' + value + '}');
if(addMoreOptions != null) {
var textObject = JSON.stringify(object);
textObject = textObject.substring(1,textObject.length-1);
var AddElement = JSON.stringify(addMoreOptions);
object = eval('{' + textObject +','+ AddElement.substring(1,AddElement.length-1) + '}');
}
return object;
}
addValueInObject('sdfasfas', yourObject, 'keyname');
OR:
var obj = {'key':'value'};
obj.key2 = 'value2';
If you are using generics, all answer will give us compile error. You can use return default(T);
. Sample below to explain further.
public async Task<T> GetItemAsync<T>(string id)
{
try
{
var response = await this._container.ReadItemAsync<T>(id, new PartitionKey(id));
return response.Resource;
}
catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return default(T);
}
}
Also added the dll to the test project (through Nuget Manager) and it fixed it.
This is just a sample code, but it may help you get on your way:
Public Sub testIt()
Workbooks("Workbook2").Activate
ActiveWorkbook.Sheets("Sheet2").Activate
ActiveSheet.Range("B3").Select
ActiveCell.EntireRow.Insert
End Sub
I am assuming that you can open the book (called Workbook2
in the example).
I think (but I'm not sure) you can squash all this in a single line of code:
Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert
This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.
http://www.boutell.com/newfaq/creating/include.html
this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways
The manual for json_encode specifies this:
All string data must be UTF-8 encoded.
Thus, try array_map
ping utf8_encode()
to your array before you encode it:
$arr = array_map('utf8_encode', $arr);
$json = json_encode($arr);
// {"funds":"ComStage STOXX\u00c2\u00aeEurope 600 Techn NR ETF"}
For reference, take a look at the differences between the three examples on this fiddle. The first doesn't use character encoding, the second uses htmlentities
and the third uses utf8_encode
- they all return different results.
For consistency, you should use utf8_encode()
.
Docs
function trimNumber(num, len) {
const modulu_one = 1;
const start_numbers_float=2;
var int_part = Math.trunc(num);
var float_part = String(num % modulu_one);
float_part = float_part.slice(start_numbers_float, start_numbers_float+len);
return int_part+'.'+float_part;
}
Use (localdb)\MSSQLLocalDB
. That is the LocalDB instance intended for applications, independent of Visual Studio version.
Disregard my original answer: "With SQL Server 2014 Express LocalDB, use (localdb)\ProjectsV12
. This works in both Visual Studio 2013 and SQL Server 2014 Management Studio." While ProjectsV12 will indeed give you a LocalDB instance, it's the wrong one, intended for use by SQL Server Data Tools.