If you want your JTextField
to be focused when your GUI shows up, you can use this:
in = new JTextField(40);
f.addWindowListener( new WindowAdapter() {
public void windowOpened( WindowEvent e ){
in.requestFocus();
}
});
Where f
would be your JFrame
and in
is your JTextField
.
xyz.setColumns() method is control the width of TextField.
import java.awt.*;
import javax.swing.*;
class miniproj extends JFrame {
public static void main(String[] args)
{
JFrame frame=new JFrame();
JPanel panel=new JPanel();
frame.setSize(400,400);
frame.setTitle("Registration");
JLabel lablename=new JLabel("Enter your name");
TextField tname=new TextField(30);
tname.setColumns(45);
JLabel lableemail=new JLabel("Enter your Email");
TextField email=new TextField(30);
email.setColumns(45);
JLabel lableaddress=new JLabel("Enter your address");
TextField address=new TextField(30);
address.setColumns(45);
address.setFont(Font.getFont(Font.SERIF));
JLabel lablepass=new JLabel("Enter your password");
TextField pass=new TextField(30);
pass.setColumns(45);
JButton login=new JButton();
JButton create=new JButton();
login.setPreferredSize(new Dimension(90,30));
login.setText("Login");
create.setPreferredSize(new Dimension(90,30));
create.setText("Create");
panel.add(lablename);
panel.add(tname);
panel.add(lableemail);
panel.add(email);
panel.add(lableaddress);
panel.add(address);
panel.add(lablepass);
panel.add(pass);
panel.add(create);
panel.add(login);
frame.add(panel);
frame.setVisible(true);
}
}
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt)
{
if(jTextField1.getText().length()>=5)
{
jTextField1.setText(jTextField1.getText().substring(0, 4));
}
}
I have taken a jtextfield whose name is jTextField1, the code is in its key pressed event. I Have tested it and it works. And I am using the NetBeans IDE.
Here is a single class copy/paste solution:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.plaf.basic.BasicTextFieldUI;
import javax.swing.text.JTextComponent;
public class HintTextFieldUI extends BasicTextFieldUI implements FocusListener {
private String hint;
private boolean hideOnFocus;
private Color color;
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
repaint();
}
private void repaint() {
if(getComponent() != null) {
getComponent().repaint();
}
}
public boolean isHideOnFocus() {
return hideOnFocus;
}
public void setHideOnFocus(boolean hideOnFocus) {
this.hideOnFocus = hideOnFocus;
repaint();
}
public String getHint() {
return hint;
}
public void setHint(String hint) {
this.hint = hint;
repaint();
}
public HintTextFieldUI(String hint) {
this(hint,false);
}
public HintTextFieldUI(String hint, boolean hideOnFocus) {
this(hint,hideOnFocus, null);
}
public HintTextFieldUI(String hint, boolean hideOnFocus, Color color) {
this.hint = hint;
this.hideOnFocus = hideOnFocus;
this.color = color;
}
@Override
protected void paintSafely(Graphics g) {
super.paintSafely(g);
JTextComponent comp = getComponent();
if(hint!=null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))){
if(color != null) {
g.setColor(color);
} else {
g.setColor(comp.getForeground().brighter().brighter().brighter());
}
int padding = (comp.getHeight() - comp.getFont().getSize())/2;
g.drawString(hint, 2, comp.getHeight()-padding-1);
}
}
@Override
public void focusGained(FocusEvent e) {
if(hideOnFocus) repaint();
}
@Override
public void focusLost(FocusEvent e) {
if(hideOnFocus) repaint();
}
@Override
protected void installListeners() {
super.installListeners();
getComponent().addFocusListener(this);
}
@Override
protected void uninstallListeners() {
super.uninstallListeners();
getComponent().removeFocusListener(this);
}
}
Use it like this:
TextField field = new JTextField();
field.setUI(new HintTextFieldUI("Search", true));
Note that it is happening in protected void paintSafely(Graphics g)
.
I would recommend using Glazed Lists for this. It makes it very easy to map a data structure to a table model.
To react to the mouseclick on the JTable, use an ActionListener: ActionListener on JLabel or JTable cell
From the api on GridLayout:
The container is divided into equal-sized rectangles, and one component is placed in each rectangle.
Try using FlowLayout or GridBagLayout for your set size to be meaningful. Also, @Serplat is correct. You need to use setPreferredSize( Dimension ) instead of setSize( int, int ).
JPanel displayPanel = new JPanel();
// JPanel displayPanel = new JPanel( new GridLayout( 4, 2 ) );
// JPanel displayPanel = new JPanel( new BorderLayout() );
// JPanel displayPanel = new JPanel( new GridBagLayout() );
JTextField titleText = new JTextField( "title" );
titleText.setPreferredSize( new Dimension( 200, 24 ) );
// For FlowLayout and GridLayout, uncomment:
displayPanel.add( titleText );
// For BorderLayout, uncomment:
// displayPanel.add( titleText, BorderLayout.NORTH );
// For GridBagLayout, uncomment:
// displayPanel.add( titleText, new GridBagConstraints( 0, 0, 1, 1, 1.0,
// 1.0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
// new Insets( 0, 0, 0, 0 ), 0, 0 ) );
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
A JTextField
was designed to use an ActionListener
just like a JButton
is. See the addActionListener()
method of JTextField
.
For example:
Action action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
System.out.println("some action");
}
};
JTextField textField = new JTextField(10);
textField.addActionListener( action );
Now the event is fired when the Enter key is used.
Also, an added benefit is that you can share the listener with a button even if you don't want to make the button a default button.
JButton button = new JButton("Do Something");
button.addActionListener( action );
Note, this example uses an Action
, which implements ActionListener
because Action
is a newer API with addition features. For example you could disable the Action
which would disable the event for both the text field and the button.
For that you need to add change listener (a DocumentListener
which reacts for change in the text) for your JTextField
, and within actionPerformed()
, you need to update the loginButton
to enabled/disabled depending on the whether the JTextfield
is empty or not.
Below is what I found from this thread.
yourJTextField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
changed();
}
public void removeUpdate(DocumentEvent e) {
changed();
}
public void insertUpdate(DocumentEvent e) {
changed();
}
public void changed() {
if (yourJTextField.getText().equals("")){
loginButton.setEnabled(false);
}
else {
loginButton.setEnabled(true);
}
}
});
// to string
String text = textField.getText();
// to JTextField
textField.setText(text);
You can also create a new text field: new JTextField(text)
Note that this is not conversion. You have two objects, where one has a property of the type of the other one, and you just set/get it.
Reference: javadocs of JTextField
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.
The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.
For example: using-documentfilter-filterbypass
Also for tutorial help, please look at: Implementing a DocumentFilter.
Edit
For instance:
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
public class DocFilter {
public static void main(String[] args) {
JTextField textField = new JTextField(10);
JPanel panel = new JPanel();
panel.add(textField);
PlainDocument doc = (PlainDocument) textField.getDocument();
doc.setDocumentFilter(new MyIntFilter());
JOptionPane.showMessageDialog(null, panel);
}
}
class MyIntFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
if (test(sb.toString())) {
super.insertString(fb, offset, string, attr);
} else {
// warn the user and don't allow the insert
}
}
private boolean test(String text) {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
if (test(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
} else {
// warn the user and don't allow the insert
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.delete(offset, offset + length);
if (test(sb.toString())) {
super.remove(fb, offset, length);
} else {
// warn the user and don't allow the insert
}
}
}
Why is this important?
If we use runnable method SwingUtilities.invokeLater() while using Document listener application is getting stuck sometimes and taking time to update the result(As per my experiment). Instead of that we can also use KeyReleased event for text field change listener as mentioned here.
usernameTextField.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
JTextField textField = (JTextField) e.getSource();
String text = textField.getText();
textField.setText(text.toUpperCase());
}
});
Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT
i.e 204 No Content as in place of HttpStatus.OK
The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.
Any value of T will be ignored for 204, but not for 404
public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$
if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
} else {
LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
}
}
I built quicktype exactly for this purpose. Just paste your sample JSON and quicktype generates this type hierarchy for your API data:
struct Forecast {
let hourly: Hourly
let daily: Daily
let currently: Currently
let flags: Flags
let longitude: Double
let latitude: Double
let offset: Int
let timezone: String
}
struct Hourly {
let icon: String
let data: [Currently]
let summary: String
}
struct Daily {
let icon: String
let data: [Datum]
let summary: String
}
struct Datum {
let precipIntensityMax: Double
let apparentTemperatureMinTime: Int
let apparentTemperatureLowTime: Int
let apparentTemperatureHighTime: Int
let apparentTemperatureHigh: Double
let apparentTemperatureLow: Double
let apparentTemperatureMaxTime: Int
let apparentTemperatureMax: Double
let apparentTemperatureMin: Double
let icon: String
let dewPoint: Double
let cloudCover: Double
let humidity: Double
let ozone: Double
let moonPhase: Double
let precipIntensity: Double
let temperatureHigh: Double
let pressure: Double
let precipProbability: Double
let precipIntensityMaxTime: Int
let precipType: String?
let sunriseTime: Int
let summary: String
let sunsetTime: Int
let temperatureMax: Double
let time: Int
let temperatureLow: Double
let temperatureHighTime: Int
let temperatureLowTime: Int
let temperatureMin: Double
let temperatureMaxTime: Int
let temperatureMinTime: Int
let uvIndexTime: Int
let windGust: Double
let uvIndex: Int
let windBearing: Int
let windGustTime: Int
let windSpeed: Double
}
struct Currently {
let precipProbability: Double
let humidity: Double
let cloudCover: Double
let apparentTemperature: Double
let dewPoint: Double
let ozone: Double
let icon: String
let precipIntensity: Double
let temperature: Double
let pressure: Double
let precipType: String?
let summary: String
let uvIndex: Int
let windGust: Double
let time: Int
let windBearing: Int
let windSpeed: Double
}
struct Flags {
let sources: [String]
let isdStations: [String]
let units: String
}
It also generates dependency-free marshaling code to coax the return value of JSONSerialization.jsonObject
into a Forecast
, including a convenience constructor that takes a JSON string so you can quickly parse a strongly typed Forecast
value and access its fields:
let forecast = Forecast.from(json: jsonString)!
print(forecast.daily.data[0].windGustTime)
You can install quicktype from npm with npm i -g quicktype
or use the web UI to get the complete generated code to paste into your playground.
Model.pluck("DISTINCT column_name")
Note that the function will ONLY work on STRING objects.
For instance, I was consuming a plugin, and was confused why I was getting a "extension.tolowercase is not a function" JS error.
onChange: function(file, extension)
{
alert("extension.toLowerCase()=>" + extension.toLowerCase() + "<=");
Which produced the error "extension.toLowerCase is not a function" So I tried this piece of code, which revealed the problem!
alert("(typeof extension)=>" + (typeof extension) + "<=");;
The output was"(typeof extension)=>object<=" - so AhHa, I was NOT getting a string var for my input. The fix is straight forward though - just force the darn thing into a String!:
var extension = String(extension);
After the cast, the extension.toLowerCase() function worked fine.
You should use partial views. I use the following approach:
Use a view model so you're not passing your domain models to your views:
public class EditPersonViewModel
{
public int Id { get; set; } // this is only used to retrieve record from Db
public string Name { get; set; }
public string Age { get; set; }
}
In your PersonController:
[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{
var viewModel = new EditPersonViewModel();
viewModel.Id = id;
return PartialView("_EditPersonPartial", viewModel);
}
[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
if (ModelState.IsValid)
{
var toUpdate = personRepo.Find(viewModel.Id);
toUpdate.Name = viewModel.Name;
toUpdate.Age = viewModel.Age;
personRepo.InsertOrUpdate(toUpdate);
personRepo.Save();
return View("Index");
}
}
Next create a partial view called _EditPersonPartial
. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.
@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "list-of-people"
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
<div class="modal-body">
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
</div>
<div class="modal-footer">
<button class="btn btn-inverse" type="submit">Save</button>
</div>
}
Now somewhere in your application, say another partial _peoplePartial.cshtml etc:
<div>
@foreach(var person in Model.People)
{
<button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
}
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
<div id="edit-person-container"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.edit-person').click(function () {
var url = "/Person/EditPerson"; // the url to the controller
var id = $(this).attr('data-id'); // the id that's given to each button in the list
$.get(url + '/' + id, function (data) {
$('#edit-person-container').html(data);
$('#edit-person').modal('show');
});
});
});
</script>
use contains() method which is available in list interface to check the value exists in list or not.If it contains that element, get its index and remove it
You can change from the property of every item.
You can annotate a class or a method with SuppressWarnings
@java.lang.SuppressWarnings("squid:S00112")
squid:S00112 in this case is a Sonar issue ID. You can find this ID in the Sonar UI. Go to Issues Drilldown. Find an issue you want to suppress warnings on. In the red issue box in your code is there a Rule link with a definition of a given issue. Once you click that you will see the ID at the top of the page.
In our case, everything LOOKED ok, but it took most of the day to figure this out:
TLDR: Check your certificate paths to make sure the root certificate is correct. In the case of COMODO certificates, it should say "USERTrust" and be issued by "AddTrust External CA Root". NOT "COMODO" issued by "COMODO RSA Certification Authority".
From the CloudFront docs: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/SecureConnections.html
If the origin server returns an invalid certificate or a self-signed certificate, or if the origin server returns the certificate chain in the wrong order, CloudFront drops the TCP connection, returns HTTP error code 502, and sets the X-Cache header to Error from cloudfront.
We had the right ciphers enabled as per: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html#RequestCustomEncryption
Our certificate was valid according to Google, Firefox and ssl-checker: https://www.sslshopper.com/ssl-checker.html
However the last certificate in the ssl checker chain was "COMODO RSA Domain Validation Secure Server CA", issued by "COMODO RSA Certification Authority"
It seems that CloudFront does not hold the certificate for "COMODO RSA Certification Authority" and as such thinks the certificate provided by the origin server is self signed.
This was working for a long time before apparently suddenly stopping. What happened was I had just updated our certificates for the year, but during the import, something was changed in the certificate path for all the previous certificates. They all started referencing "COMODO RSA Certification Authority" whereas before the chain was longer and the root was "AddTrust External CA Root".
Because of this, switching back to the older cert did not fix the cloudfront issue.
I had to delete the extra certificate named "COMODO RSA Certification Authority", the one that did not reference AddTrust. After doing this, all my website certificates' paths updated to point back to AddTrust/USERTrust again. Note can also open up the bad root certificate from the path, click "Details" -> "Edit Properties" and then disable it that way. This updated the path immediately. You may also need to delete multiple copies of the certificate, found under "Personal" and "Trusted Root Certificate Authorities"
Finally I had to re select the certificate in IIS to get it to serve the new certificate chain.
After all this, ssl-checker started displaying a third certificate in the chain, which pointed back to "AddTrust External CA Root"
Finally, CloudFront accepted the origin server's certificate and the provided chain as being trusted. Our CDN started working correctly again!
To prevent this happening in the future, we will need to export our newly generated certificates from a machine with the correct certificate chain, i.e. distrust or delete the certificate "COMODO RSA Certification Authroity" issued by "COMODO RSA Certification Authroity" (expiring in 2038). This only seems to affect windows machines, where this certificate is installed by default.
Use the SC command, like this (you need to be on a command prompt to execute the commands in this post):
SC STOP shortservicename
SC DELETE shortservicename
Note: You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". Note to PowerShell users: sc
is aliased to set-content
. So sc delete service
will actually create a file called delete
with the content service
. To do this in Powershell, use sc.exe delete service
instead
If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:
SC QUERY state= all >"C:\Service List.txt"
For a more concise list, execute this command:
SC QUERY state= all | FIND "_NAME"
The short service name will be listed just above the display name, like this:
SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service
And thus to delete that service:
SC STOP MyService
SC DELETE MyService
When we have to send multiple trigger parameters to jenkins job, the following commands works.
curl -X POST -i -u "auto_user":"xxxauthentication_tokenxxx" "JENKINS_URL/view/tests/job/helloworld/buildWithParameters?param1=162¶m2=store"
You can also take a look at PDFMiner (or for older versions of Python see PDFMiner and PDFMiner).
A particular feature of interest in PDFMiner is that you can control how it regroups text parts when extracting them. You do this by specifying the space between lines, words, characters, etc. So, maybe by tweaking this you can achieve what you want (that depends of the variability of your documents). PDFMiner can also give you the location of the text in the page, it can extract data by Object ID and other stuff. So dig in PDFMiner and be creative!
But your problem is really not an easy one to solve because, in a PDF, the text is not continuous, but made from a lot of small groups of characters positioned absolutely in the page. The focus of PDF is to keep the layout intact. It's not content oriented but presentation oriented.
Change data type of DataFrame column:
To int:
df.column_name = df.column_name.astype(np.int64)
To str:
df.column_name = df.column_name.astype(str)
If all above point not work. Then try this one. I tried it. It's working for me.
UPDATE 2017
For new versions of apache the file is called apache2.conf
So to access the file, type sudo nano /etc/apache2/apache2.conf and change the correspondent line inside block <Directory /var/www >
I had this issue on Android 10,
Changed targetSdkVersion 29
to targetSdkVersion 28
issue resolved. Not sure what is the actual problem.
I think not a good practice, but it worked.
before:
compileSdkVersion 29
minSdkVersion 14
targetSdkVersion 29
Now:
compileSdkVersion 29
minSdkVersion 14
targetSdkVersion 28
Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.
Digest Access Authentication uses the hashing methodologies to generate the cryptographic result
None of the previous solutions work correctly... I have tried all the ways, but it did not give me the expected result... At last I found that there are some errors in the code... And the full code is given below.
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(23.00, 90.00),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
@foreach (var item in Model)
{
<text>
var markerlatLng = new google.maps.LatLng(@(item.LATITUDE), @(item.LONGITUDE));
var title = '@(item.EMP_ID)';
var description = '@(item.TIME)';
var contentString = '<h3>' + "Employee " +title+ " was here at "+description+ '</h3>' + '<p>'+" "+ '</p>'
var infowindow = new google.maps.InfoWindow({
// content: contentString
});
var marker = new google.maps.Marker({
position: markerlatLng,
title: title,
map: map,
draggable: false,
content: contentString
});
google.maps.event.addListener(marker, 'click', (function (marker) {
return function () {
infowindow.setContent(marker.content);
infowindow.open(map, marker);
}
})(marker));
</text>
}
</script>
You should use the string replace function, with a single regex. Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";_x000D_
console.log(str.replace(/[^a-zA-Z ]/g, ""));
_x000D_
Use the INTERVAL
type to it. E.g:
--yesterday
SELECT NOW() - INTERVAL '1 DAY';
--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;
Then you can do the following on your query:
SELECT
org_id,
count(accounts) AS COUNT,
((date_at) - INTERVAL '1 DAY') AS dateat
FROM
sourcetable
WHERE
date_at <= now() - INTERVAL '130 DAYS'
GROUP BY
org_id,
dateat;
You can append multiple operands. E.g.: how to get last day of current month?
SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';
You can also create an interval using make_interval
function, useful when you need to create it at runtime (not using literals):
SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);
i had a situation to work generic now and used this:
class Test {
// your class definition
}
nameByType = function(type){
return type.prototype["constructor"]["name"];
};
console.log(nameByType(Test));
thats the only way i found to get the class name by type input if you don't have a instance of an object.
(written in ES2017)
dot notation also works fine
console.log(Test.prototype.constructor.name); // returns "Test"
Yes. But remember that such primary key allow NULL
values in both columns multiple times.
Create a table as such:
sqlite> CREATE TABLE something (
column1, column2, value, PRIMARY KEY (column1, column2));
Now this works without any warning:
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> insert into something (value) VALUES ('bla-bla');
sqlite> select * from something;
NULL|NULL|bla-bla
NULL|NULL|bla-bla
run command to see:
javac -version
Also you can verify manually by going to the specific location and then check. To do this run below command in the mac terminal
cd /Library/Java/JavaVirtualMachines/
Then run ls
command in the terminal again. Now you can see the jdk version & package if exists in your computer.
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:
.
You can convert between the two like this:
NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease];
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
BOOL success = [dict writeToFile:@"/file/path" atomically:YES];
To read a dictionary from a file, there's a corresponding method:
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];
If you want to read the file as an NSMutableDictionary, simply use:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.
It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult.
You may want to consider posting your second question in another topic.
The easiest way is to convert to a date:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as this and this.
I would be inclined to use the following, just out of habit:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
What do you mean by a long date type?
You can cast a long to a double:
double d = (double) 15552451L;
That's a great example. When ¤t
is parsed into a text node it is converted to ¤t
. When parsed into an attribute value, it is parsed as ¤t
.
If you want ¤t
in a text node, you should write &current
in your markup.
The gory details are in the HTML5 parsing spec - Named Character Reference State
Same origin policy has nothing to do with sending request to another url (different protocol or domain or port).
It is all about restricting access to (reading) response data from another url. So JavaScript code within a page can post to arbitrary domain or submit forms within that page to anywhere (unless the form is in an iframe with different url).
But what makes these POST requests inefficient is that these requests lack antiforgery tokens, so are ignored by the other url. Moreover, if the JavaScript tries to get that security tokens, by sending AJAX request to the victim url, it is prevented to access that data by Same Origin Policy.
A good example: here
And a good documentation from Mozilla: here
Total cursors open, by session:
select a.value, s.username, s.sid, s.serial#
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic# and s.sid=a.sid
and b.name = 'opened cursors current';
Source: http://www.orafaq.com/node/758
As far as I know queries on v$ views are based on pseudo-tables ("x$" tables) that point directly to the relevant portions of the SGA, so you can't get more accurate than that; however this also means that it is point-in-time (i.e. dirty read).
Replace
import { Router, Route, Link, browserHistory } from 'react-router';
With
import { BrowserRouter as Router, Route } from 'react-router-dom';
It will start working. It is because react-router-dom exports BrowserRouter
It's syntactically correct and stylistically okay.
Good style requires every case:
statement should end with one of the following:
break;
continue;
return (x);
exit (x);
throw (x);
//fallthrough
Additionally, following case (x):
immediately with
case (y):
default:
is permissible - bundling several cases that have exactly the same effect.
Anything else is suspected to be a mistake, just like if(a=4){...}
Of course you need enclosing loop (while
, for
, do...while
) for continue
to work. It won't loop back to case()
alone. But a construct like:
while(record = getNewRecord())
{
switch(record.type)
{
case RECORD_TYPE_...;
...
break;
default: //unknown type
continue; //skip processing this record altogether.
}
//...more processing...
}
...is okay.
Secure_path is your friend, but if you want to exempt yourself from secure_path just do
sudo visudo
And append
Defaults exempt_group=your_goup
If you want to exempt a bunch of users create a group, add all the users to it, and use that as your exempt_group. man 5 sudoers for more.
JPA will use all properties of the class, unless you specifically mark them with @Transient
:
@Transient
private String agencyName;
The @Column
annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the length
attribute of @Column
is only used when auto-generating table definitions, it has no effect on the runtime.
Amongst the other fixes, I had the error come up when I tried to do Product->Archive. Turns out I had this :
Objective-C Bridging Header
Debug (had the value)
Release (had the value)
Any architecture | Any SDK (this was blank - problem here!)
After setting it in that last line, it worked.
You can use SHOW
:
SHOW max_connections;
This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf
as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf
in your current session:
RESET max_connections;
However, not applicable to this particular setting. The manual:
This parameter can only be set at server start.
To see all settings:
SHOW ALL;
There is also pg_settings
:
The view
pg_settings
provides access to run-time parameters of the server. It is essentially an alternative interface to theSHOW
andSET
commands. It also provides access to some facts about each parameter that are not directly available fromSHOW
, such as minimum and maximum values.
For your original request:
SELECT *
FROM pg_settings
WHERE name = 'max_connections';
Finally, there is current_setting()
, which can be nested in DML statements:
SELECT current_setting('max_connections');
Related:
I'm using cyanogenmod 7.2 on android 2.3.4, then just open terminal emulator and type:
$ ip addr show
$ ip route show
rev {
int len = strlen(str)-1;
for ( int i =0; i< len/2 ; i++ ) {
char t = str[i];
str[i] = str[len-i];
str[len-i] = t;
}
}
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete
;
Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
You can always try putting this code in your main css without modifying the bootstrap file what is most recommended so you keep consistency if in a future you update the bootstrap file.
.tooltip-inner {
background-color: #FF0000;
}
.tooltip.right .tooltip-arrow {
border-right: 5px solid #FF0000;
}
Notice that this example is for a right tooltip. The tooltip-inner property changes the tooltip BG color, the other one changes the arrow color.
First: Even the unique IDs generated by java UUID.randomUUID or .net GUID are not 100% unique. Especialy UUID.randomUUID is "only" a 128 bit (secure) random value. So if you reduce it to 64 bit, 32 bit, 16 bit (or even 1 bit) then it becomes simply less unique.
So it is at least a risk based decisions, how long your uuid must be.
Second: I assume that when you talk about "only 8 characters" you mean a String of 8 normal printable characters.
If you want a unique string with length 8 printable characters you could use a base64 encoding. This means 6bit per char, so you get 48bit in total (possible not very unique - but maybe it is ok for you application)
So the way is simple: create a 6 byte random array
SecureRandom rand;
// ...
byte[] randomBytes = new byte[16];
rand.nextBytes(randomBytes);
And then transform it to a Base64 String, for example by org.apache.commons.codec.binary.Base64
BTW: it depends on your application if there is a better way to create "uuid" then by random. (If you create a the UUIDs only once per second, then it is a good idea to add a time stamp) (By the way: if you combine (xor) two random values, the result is always at least as random as the most random of the both).
Let'e me give an example:
client connect to server, and send 1MB data to server every 1 second.
server side accept a connection, and then sleep 20 second, without recv msg from client.So the tcp send buffer
in the client side will be full.
Code in client side:
#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...) \
if (r) { \
printf(__VA_ARGS__); \
printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
exit(1); \
}
void setNonBlock(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
exit_if(flags < 0, "fcntl failed");
int r = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
exit_if(r < 0, "fcntl failed");
}
void test_full_sock_buf_1(){
short port = 8000;
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
int fd = socket(AF_INET, SOCK_STREAM, 0);
exit_if(fd<0, "create socket error");
int ret = connect(fd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
exit_if(ret<0, "connect to server error");
setNonBlock(fd);
printf("connect to server success");
const int LEN = 1024 * 1000;
char msg[LEN]; // 1MB data
memset(msg, 'a', LEN);
for (int i = 0; i < 1000; ++i) {
int len = send(fd, msg, LEN, 0);
printf("send: %d, erron: %d, %s \n", len, errno, strerror(errno));
sleep(1);
}
}
int main(){
test_full_sock_buf_1();
return 0;
}
Code in server side:
#include <arpa/inet.h>
#include <sys/socket.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#define exit_if(r, ...) \
if (r) { \
printf(__VA_ARGS__); \
printf("%s:%d error no: %d error msg %s\n", __FILE__, __LINE__, errno, strerror(errno)); \
exit(1); \
}
void test_full_sock_buf_1(){
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
exit_if(listenfd<0, "create socket error");
short port = 8000;
struct sockaddr_in addr;
memset(&addr, 0, sizeof addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
int r = ::bind(listenfd, (struct sockaddr *) &addr, sizeof(struct sockaddr));
exit_if(r<0, "bind socket error");
r = listen(listenfd, 100);
exit_if(r<0, "listen socket error");
struct sockaddr_in raddr;
socklen_t rsz = sizeof(raddr);
int cfd = accept(listenfd, (struct sockaddr *) &raddr, &rsz);
exit_if(cfd<0, "accept socket error");
sockaddr_in peer;
socklen_t alen = sizeof(peer);
getpeername(cfd, (sockaddr *) &peer, &alen);
printf("accept a connection from %s:%d\n", inet_ntoa(peer.sin_addr), ntohs(peer.sin_port));
printf("but now I will sleep 15 second, then exit");
sleep(15);
}
Start server side, then start client side.
server side may output:
accept a connection from 127.0.0.1:35764
but now I will sleep 15 second, then exit
Process finished with exit code 0
client side may output:
connect to server successsend: 1024000, erron: 0, Success
send: 1024000, erron: 0, Success
send: 1024000, erron: 0, Success
send: 552190, erron: 0, Success
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 11, Resource temporarily unavailable
send: -1, erron: 104, Connection reset by peer
send: -1, erron: 32, Broken pipe
send: -1, erron: 32, Broken pipe
send: -1, erron: 32, Broken pipe
send: -1, erron: 32, Broken pipe
send: -1, erron: 32, Broken pipe
You can see, as the server side doesn't recv the data from client, so when the client side tcp buffer
get full, but you still send data, so you may get Resource temporarily unavailable
error.
You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:
new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));
If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:
new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));
I will break answer on three paragraphs.
Part 1:
git stash
(To save your un-committed changes in a "stash". Note: this removes changes from working tree!)
git checkout some_branch
(change to intended branch -- in this case some_branch
)
git stash list
(list stashes)
You can see:
stash@{0}: WIP on {branch_name}: {SHA-1 of last commit} {last commit of you branch}
stash@{0}: WIP on master: 085b095c6 modification for test
git stash apply
(to apply stash to working tree in current branch)
git stash apply stash@{12}
(if you will have many stashes you can choose what stash will apply -- in this case we apply stash 12
)
git stash drop stash@{0}
(to remove from stash list -- in this case stash 0
)
git stash pop stash@{1}
(to apply selected stash and drop it from stash list)
Part 2:
You can hide your changes with this command but it is not necessary.
You can continue on the next day without stash.
This commands for hide your changes and work on different branches or for implementation some realisation of your code and save in stashes without branches and commitsor your custom case!
And later you can use some of stashes and check wich is better.
Part 3:
Stash command for local hide your changes.
If you want work remotely you must commit and push.
We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.
some method to call when making post requests....
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
});
SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
HttpPost postRequest = new HttpPost(url);
continue your request in the normal form
Just adding to the great answer from @Shawn. If you are using dotnet 5 you need to update the class to be:
public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var attributes = new List<TAttribute>();
if (context.Resource is HttpContext httpContext)
{
var endPoint = httpContext.GetEndpoint();
var action = endPoint?.Metadata.GetMetadata<ControllerActionDescriptor>();
if(action != null)
{
attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
attributes.AddRange(GetAttributes(action.MethodInfo));
}
}
return HandleRequirementAsync(context, requirement, attributes);
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);
private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo) => memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
}
Noting the way getting the ControllerActionDescriptor has changed.
Adding my bit as well, should anybody struggle like me, notice that methods is a case-sensitive word:
<template>
<span>{{name}}</span>
</template>
<script>
export default {
name: "MyComponent",
Methods: {
name() {return '';}
}
</script>
'Methods' should be 'methods'
You can use this code instead.
<div id="" style="overflow-y:scroll; overflow-x:hidden; height:400px;">
overflow-x: The overflow-x property specifies what to do with the left/right edges of the content - if it overflows the element's content area.
overflow-y: The overflow-y property specifies what to do with the top/bottom edges of the content - if it overflows the element's content area.
Values
visible: Default value. The content is not clipped, and it may be rendered outside the content box.
hidden: The content is clipped - and no scrolling mechanism is provided.
scroll: The content is clipped and a scrolling mechanism is provided.
auto: Should cause a scrolling mechanism to be provided for overflowing boxes.
initial: Sets this property to its default value.
inherit Inherits this property from its parent element.
There is no interoperable way to encode non-ASCII names in Content-Disposition
. Browser compatibility is a mess.
The theoretically correct syntax for use of UTF-8 in Content-Disposition
is very weird: filename*=UTF-8''foo%c3%a4
(yes, that's an asterisk, and no quotes except an empty single quote in the middle)
This header is kinda-not-quite-standard (HTTP/1.1 spec acknowledges its existence, but doesn't require clients to support it).
There is a simple and very robust alternative: use a URL that contains the filename you want.
When the name after the last slash is the one you want, you don't need any extra headers!
This trick works:
/real_script.php/fake_filename.doc
And if your server supports URL rewriting (e.g. mod_rewrite
in Apache) then you can fully hide the script part.
Characters in URLs should be in UTF-8, urlencoded byte-by-byte:
/mot%C3%B6rhead # motörhead
IUSR is part of IIS_IUSER group.so i guess you can remove the permissions for IUSR without worrying. Further Reading
However, a problem arose over time as more and more Windows system services started to run as NETWORKSERVICE. This is because services running as NETWORKSERVICE can tamper with other services that run under the same identity. Because IIS worker processes run third-party code by default (Classic ASP, ASP.NET, PHP code), it was time to isolate IIS worker processes from other Windows system services and run IIS worker processes under unique identities. The Windows operating system provides a feature called "Virtual Accounts" that allows IIS to create unique identities for each of its Application Pools. DefaultAppPool is the by default pool that is assigned to all Application Pool you create.
To make it more secure you can change the IIS DefaultAppPool Identity to ApplicationPoolIdentity.
Regarding permission, Create and Delete summarizes all the rights that can be given. So whatever you have assigned to the IIS_USERS group is that they will require. Nothing more, nothing less.
hope this helps.
Create "libs" folder in app directory copy your jar file in libs folder right click on your jar file in Android Studio and Add As library... Then open build.gradle and add this:
dependencies {
implementation files('libs/your jar file.jar')
}
Screams in to the void - just "no" don't do it. This is a dumb idea.
Integrating with external data sources is what SSIS is for, or write a dot net application/service which queries the box and makes the API calls.
Writing CLR code to enable a SQL process to call web-services is the sort of thing that can bring a SQL box to its knees if done badly - imagine putting the the CLR function in a view somewhere - later someone else comes along not knowing what you've donem and joins on that view with a million row table - suddenly your SQL box is making a million individual webapi calls.
The whole idea is insane.
This doing sort of thing is the reason that enterprise DBAs dont' trust developers.
CLR is the kind of great power, which brings great responsibility, and the above is an abuse of it.
uniq would be fooled by trailing spaces and tabs. In order to emulate how a human makes comparison, I am trimming all trailing spaces and tabs before comparison.
I think that the $!N; needs curly braces or else it continues, and that is the cause of infinite loop.
I have bash 5.0 and sed 4.7 in Ubuntu 20.10. The second one-liner did not work, at the character set match.
Three variations, first to eliminate adjacent repeat lines, second to eliminate repeat lines wherever they occur, third to eliminate all but the last instance of lines in file.
# First line in a set of duplicate lines is kept, rest are deleted.
# Emulate human eyes on trailing spaces and tabs by trimming those.
# Use after norepeat() to dedupe blank lines.
dedupe() {
sed -E '
$!{
N;
s/[ \t]+$//;
/^(.*)\n\1$/!P;
D;
}
';
}
# Delete duplicate, nonconsecutive lines from a file. Ignore blank
# lines. Trailing spaces and tabs are trimmed to humanize comparisons
# squeeze blank lines to one
norepeat() {
sed -n -E '
s/[ \t]+$//;
G;
/^(\n){2,}/d;
/^([^\n]+).*\n\1(\n|$)/d;
h;
P;
';
}
lastrepeat() {
sed -n -E '
s/[ \t]+$//;
/^$/{
H;
d;
};
G;
# delete previous repeated line if found
s/^([^\n]+)(.*)(\n\1(\n.*|$))/\1\2\4/;
# after searching for previous repeat, move tested last line to end
s/^([^\n]+)(\n)(.*)/\3\2\1/;
$!{
h;
d;
};
# squeeze blank lines to one
s/(\n){3,}/\n\n/g;
s/^\n//;
p;
';
}
Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.
I've done this to extend Python 2's str()
class, for instance. str()
is a particularly interesting target because of the implicit linkage to quoted data such as 'this'
and 'that'
.
Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad
bit:
extend:testDottedQuad
def testDottedQuad(strObject):
if not isinstance(strObject, basestring): return False
listStrings = strObject.split('.')
if len(listStrings) != 4: return False
for strNum in listStrings:
try: val = int(strNum)
except: return False
if val < 0: return False
if val > 255: return False
return True
After which I can write in the code fed to the preprocessor:
if '192.168.1.100'.testDottedQuad():
doSomething()
dq = '216.126.621.5'
if not dq.testDottedQuad():
throwWarning();
dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
print 'well, that was fun'
The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.
Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.
My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.
import pandas as pd
print(pd.json_normalize(your_json))
This will Normalize semi-structured JSON data into a flat table
Output
FirstName LastName MiddleName password username
John Mark Lewis 2910 johnlewis2
Answer to Question 1
Here's what I did on a Ubuntu EC2
:
A) Login as root using the keypairs
B) Setup the necessary users and their passwords with
# sudo adduser USERNAME
# sudo passwd USERNAME
C) Edit /etc/ssh/sshd_config
setting
PasswordAuthentication yes
PermitRootLogin yes
D) Restart the ssh
daemon with
# sudo service ssh restart
just change ssh to sshd if you are using centOS
Now you can login into your ec2
instance without key pairs.
The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream
. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Extern is the keyword you use to declare that the variable itself resides in another translation unit.
So you can decide to use a variable in a translation unit and then access it from another one, then in the second one you declare it as extern and the symbol will be resolved by the linker.
If you don't declare it as extern you'll get 2 variables named the same but not related at all, and an error of multiple definitions of the variable.
date = models.DateTimeField(default=datetime.now, blank=True)
A Simple but more effective way:
new FormData()
is itself like a container (or a bag). You can put everything attr or file in itself.
The only thing you'll need to append the attribute, file, fileName
eg:
let formData = new FormData()
formData.append('input', input.files[0], input.files[0].name)
and just pass it in AJAX request. Eg:
let formData = new FormData()
var d = $('#fileid')[0].files[0]
formData.append('fileid', d);
formData.append('inputname', value);
$.ajax({
url: '/yourroute',
method: 'POST',
contentType: false,
processData: false,
data: formData,
success: function(res){
console.log('successfully')
},
error: function(){
console.log('error')
}
})
You can append n number of files or data with FormData.
and if you're making AJAX Request from Script.js file to Route file in Node.js beware of using
req.body
to access data (ie text)
req.files
to access file (ie image, video etc)
Set Your Own application Path
Dim myPathsValues As String
TextBox1.Text = Application.StartupPath
TextBox2.Text = Len(Application.StartupPath)
TextBox3.Text = Microsoft.VisualBasic.Right(Application.StartupPath, 10)
myPathsValues = Val(TextBox2.Text) - 9
TextBox4.Text = Microsoft.VisualBasic.Left(Application.StartupPath, myPathsValues) & "Reports"
In my codebehind i created a checkboxlist from sql db in my Page_Load event and in my button_click event did all the get values from checkboxlist etc.
So when i checked some checkboxes and then clicked my button the first thing that happend was that my page_load event recreated the checkboxlist thus not having any boxes checked when it ran my get checkbox values... I've missed to add in the page_load event the if (!this.IsPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// db query and create checkboxlist and other
SqlConnection dbConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
string query;
try
{
query = "SELECT [name], [mail] FROM [users]";
dbConn.Open();
SqlDataAdapter da = new SqlDataAdapter(query, dbConn);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count != 0)
{
checkboxlist1.DataSource = ds;
checkboxlist1.DataTextField = "name";
checkboxlist1.DataValueField = "mail";
checkboxlist1.DataBind();
}
else
{
Response.Write("No Results found");
}
}
catch (Exception ex)
{
Response.Write("<br>" + ex);
}
finally
{
dbConn.Close();
}
}
}
protected void btnSend_Click(object sender, EventArgs e)
{
string strChkBox = string.Empty;
foreach (ListItem li in checkboxlist1.Value)
{
if (li.Selected == true)
{
strChkBox += li.Value + "; ";
// use only strChkBox += li + ", "; if you want the name of each checkbox checked rather then it's value.
}
}
Response.Write(strChkBox);
}
And the output was as expected, a semicolon separeted list for me to use in a mailsend function:
[email protected]; [email protected]; [email protected]
A long answer to a small problem. Please note that i'm far from an expert at this and know that there are better solutions then this but it might help out for some.
setTimeout("create('Hello world!', 'myfile.txt', 'text/plain')");_x000D_
function create(text, name, type) {_x000D_
var dlbtn = document.getElementById("dlbtn");_x000D_
var file = new Blob([text], {type: type});_x000D_
dlbtn.href = URL.createObjectURL(file);_x000D_
dlbtn.download = name;_x000D_
}
_x000D_
<a href="javascript:void(0)" id="dlbtn"><button>click here to download your file</button></a>
_x000D_
Common reasons for the error:
=
) instead of equality (==
/===
)foo() = 42
instead of passing arguments (foo(42)
) getFoo() = 42
instead of getFoo().theAnswer = 42
or array indexing getArray() = 42
instead of getArray()[0]= 42
In this particular case you want to use ==
(or better ===
- What exactly is Type Coercion in Javascript?) to check for equality (like if(one === "rock" && two === "rock")
, but it the actual reason you are getting the error is trickier.
The reason for the error is Operator precedence. In particular we are looking for &&
(precedence 6) and =
(precedence 3).
Let's put braces in the expression according to priority - &&
is higher than =
so it is executed first similar how one would do 3+4*5+6
as 3+(4*5)+6
:
if(one= ("rock" && two) = "rock"){...
Now we have expression similar to multiple assignments like a = b = 42
which due to right-to-left associativity executed as a = (b = 42)
. So adding more braces:
if(one= ( ("rock" && two) = "rock" ) ){...
Finally we arrived to actual problem: ("rock" && two)
can't be evaluated to l-value that can be assigned to (in this particular case it will be value of two
as truthy).
Note that if you'd use braces to match perceived priority surrounding each "equality" with braces you get no errors. Obviously that also producing different result than you'd expect - changes value of both variables and than do &&
on two strings "rock" && "rock"
resulting in "rock"
(which in turn is truthy) all the time due to behavior of logial &&:
if((one = "rock") && (two = "rock"))
{
// always executed, both one and two are set to "rock"
...
}
For even more details on the error and other cases when it can happen - see specification:
LeftHandSideExpression = AssignmentExpression
...
Throw a SyntaxError exception if the following conditions are all true:
...
IsStrictReference(lref) is true
and The Reference Specification Type explaining IsStrictReference:
... function calls are permitted to return references. This possibility is admitted purely for the sake of host objects. No built-in ECMAScript function defined by this specification returns a reference and there is no provision for a user-defined function to return a reference...
The thing that helped me:
I saw that the connection between my directory to git wasn't established -
so I did again:
git push -u origin main
if (!$('#singlechatpanel-1').css('display') == 'none') {
alert('visible');
}else{
alert('hidden');
}
For Older browsers, you need to add this line on top of HTML doc
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
As much as your available memory will allow. There's no size limit except for the heap.
It is not very nice to use native php resources like $_GET
as Laravel gives us easy ways to get the variables. As a matter of standard, whenever possible use the resources of the laravel itself instead of pure PHP.
There is at least two modes to get variables by GET in Laravel ( Laravel 5.x or greater):
Mode 1
Route:
Route::get('computers={id}', 'ComputersController@index');
Request (POSTMAN or client...):
http://localhost/api/computers=500
Controler - You can access the {id}
paramter in the Controlller by:
public function index(Request $request, $id){
return $id;
}
Mode 2
Route:
Route::get('computers', 'ComputersController@index');
Request (POSTMAN or client...):
http://localhost/api/computers?id=500
Controler - You can access the ?id
paramter in the Controlller by:
public function index(Request $request){
return $request->input('id');
}
As of API version 3.26.10, you can set the marker label with more than one characters. The restriction is lifted.
Try it, it works!
Moreover, using a MarkerLabel object instead of just a string, you can set a number of properties for the appearance, and if using a custom Icon you can set the labelOrigin property to reposition the label.
Source: https://code.google.com/p/gmaps-api-issues/issues/detail?id=8578#c30 (also, you can report any issues regarding this at the above linked thread)
It's not an array of arrays. It's an observable of observable(s).
The following returns an observable stream of string.
requestStream
.map(function(requestUrl) {
return requestUrl;
});
While this returns an observable stream of observable stream of json
requestStream
.map(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});
flatMap
flattens the observable automatically for us so we can observe the json stream directly
I had a similar issue. You won't be able to ping the VM's from external devices if using NAT setting from within VMware's networking options. I switched to bridged connection so that the guest virtual machine will get it's own IP address and and then I added a second adapter set to NAT for the guest to get to the Internet.
<a href="./">Folder</a>
In my case issue was that numberOfRowsInSection
was returning similar number of rows after calling tableView.deleteRows(...)
.
Since this was the required behaviour in my case, I ended up calling tableView.reloadData()
instead of tableView.deleteRows(...)
in cases where numberOfRowsInSection
will remain same after deleting a row.
Check your Lazy module , i haved imported AppRoutingModule in the lazy module. After removing the import and imports of AppRoutingModule, Mine started working.
import { AppRoutingModule } from '../app-routing.module';
In my case:
$('#some_link').click(function(event){
event.preventDefault();
});
$('#some_link').unbind('click');
worked as the only method to restore the default action.
As seen over here: https://stackoverflow.com/a/1673570/211514
Create a configuration file and put your entries there.
SERVER_PORT=10000
THREAD_POOL_COUNT=3
ROOT_DIR=/home/
You can load this file using Properties.load(fileName)
and retrieved values you get(key)
;
The accepted answer didn't work for me for two reasons:
BackColor
set so setting AutoSize = false
and Dock = Fill
causes the background color to fill the whole formAutoSize
set to false anyway because my label text was dynamicInstead, I simply used the form's width and the width of the label to calculate the left offset:
MyLabel.Left = (this.Width - MyLabel.Width) / 2;
SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.
if(cursor.getCount()<=0){
Log.v("tag","if 1 "+cursor.getCount());
return false;
}
Log.v("tag","2 else "+cursor.getCount());
return true;
if you not use cursor.moveToLast()
;
cursor.getCount()
always give same integer (1
) or current position of cursor.
In case you know the password of that user, or you would like to guess it, do the following:
connect user/password
If this command connects successufully, you will see the message "connected", otherwise you'd see an error message. If you are then successufull logging, that means that you know the password. In that case, just do:
alter user NAME_OF_THE_USER identified by OLD_PASSWORD;
and this will reset the password to the same password as before and also reset the account_status for that user.
You can use attributes from the System.ComponentModel.DataAnnotations
namespace to set validation rules. Refer Model Validation - By Mike Wasson for details.
Also refer video ASP.NET Web API, Part 5: Custom Validation - Jon Galloway
Other References
If the other answers are not fast enough Give this code a try:
SELECT
province, n, city, population
FROM
( SELECT @prev := '', @n := 0 ) init
JOIN
( SELECT @n := if(province != @prev, 1, @n + 1) AS n,
@prev := province,
province, city, population
FROM Canada
ORDER BY
province ASC,
population DESC
) x
WHERE n <= 3
ORDER BY province, n;
Output:
+---------------------------+------+------------------+------------+
| province | n | city | population |
+---------------------------+------+------------------+------------+
| Alberta | 1 | Calgary | 968475 |
| Alberta | 2 | Edmonton | 822319 |
| Alberta | 3 | Red Deer | 73595 |
| British Columbia | 1 | Vancouver | 1837970 |
| British Columbia | 2 | Victoria | 289625 |
| British Columbia | 3 | Abbotsford | 151685 |
| Manitoba | 1 | ...
I would say the best reference is Format for Literal IPv6 Addresses in URL's where usage of [] is defined.
Also, if it is for programming and code, specifically Java, I would suggest this readsClass for Inet6Address java/net/URL definition where usage of Inet4 address in Inet6 connotation and other cases are presented in details. For my case, IPv4-mapped address Of the form::ffff:w.x.y.z, for IPv6 address is used to represent an IPv4 address also solved my problem. It allows the native program to use the same address data structure and also the same socket when communicating with both IPv4 and IPv6 nodes. This is the case on Amazon cloud Linux boxes default setup.
The best workaround that I found creating a new Project from scratch, then import all the source files with the code. My project was not so complicated so I had no problem from there.
I'm not sure about the syntax of your specific commands (e.g., vagrant, etc), but in general...
Just register Ansible's (not-normally-shown) JSON output to a variable, then display each variable's stdout_lines
attribute:
- name: Generate SSH keys for vagrant user
user: name=vagrant generate_ssh_key=yes ssh_key_bits=2048
register: vagrant
- debug: var=vagrant.stdout_lines
- name: Show SSH public key
command: /bin/cat $home_directory/.ssh/id_rsa.pub
register: cat
- debug: var=cat.stdout_lines
- name: Wait for user to copy SSH public key
pause: prompt="Please add the SSH public key above to your GitHub account"
register: pause
- debug: var=pause.stdout_lines
How about not using regex:
// In PHP
0 !== strpos($string, 'index.php')
To figure out what the linker is looking for, run it in verbose mode.
For example, I encountered this issue while trying to compile MySQL with ZLIB support. I was receiving an error like this during compilation:
/usr/bin/ld: cannot find -lzlib
I did some Googl'ing and kept coming across different issues of the same kind where people would say to make sure the .so file actually exists and if it doesn't, then create a symlink to the versioned file, for example, zlib.so.1.2.8. But, when I checked, zlib.so DID exist. So, I thought, surely that couldn't be the problem.
I came across another post on the Internets that suggested to run make with LD_DEBUG=all:
LD_DEBUG=all make
Although I got a TON of debugging output, it wasn't actually helpful. It added more confusion than anything else. So, I was about to give up.
Then, I had an epiphany. I thought to actually check the help text for the ld command:
ld --help
From that, I figured out how to run ld in verbose mode (imagine that):
ld -lzlib --verbose
This is the output I got:
==================================================
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.a failed
attempt to open /usr/local/lib64/libzlib.so failed
attempt to open /usr/local/lib64/libzlib.a failed
attempt to open /lib64/libzlib.so failed
attempt to open /lib64/libzlib.a failed
attempt to open /usr/lib64/libzlib.so failed
attempt to open /usr/lib64/libzlib.a failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.a failed
attempt to open /usr/local/lib/libzlib.so failed
attempt to open /usr/local/lib/libzlib.a failed
attempt to open /lib/libzlib.so failed
attempt to open /lib/libzlib.a failed
attempt to open /usr/lib/libzlib.so failed
attempt to open /usr/lib/libzlib.a failed
/usr/bin/ld.bfd.real: cannot find -lzlib
Ding, ding, ding...
So, to finally fix it so I could compile MySQL with my own version of ZLIB (rather than the bundled version):
sudo ln -s /usr/lib/libz.so.1.2.8 /usr/lib/libzlib.so
Voila!
To answer this question:
:40,50s/foo/bar/g
replace foo with bar in these lines between the 40th line and the 50th line(inclusive), when execute this command you can currently in any line.
:50,40s/foo/bar/g
also works, vim will ask you for comfirm and then do the replacement for you as if you have input the first command.
:,50s/foo/bar/g
replace foo with bar in these lines between the line you are currently in and the 50th line(inclusive). (if you are in a line AFTER the 50th line vim will ask for confirm again)
To clearity the difference between vim and the vrapper plugin of Eclipse:
Note that in varpper
:,50s/foo/bar/g
command will NOT work.
:50,40s/foo/bar/g
will work without asking for comfirmation.
(For Vrapper Version 0.74.0 or older).
I got solution after using below command:
git repack -a -f -d --window=250 --depth=250
Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):
fetch(request, {mode: 'cors'});
However this still requires the server to enable CORS as well, and allow your domain to request the resource.
Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.
You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>
):
fetch(request, {mode: 'no-cors'})
.then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
Its hard to give you a good answer, without seeing the html that you are actually using.
Are you outputting a doctype / using standards mode rendering? Without actually being able to look into a html repro, that would be my first guess for a html interpretation difference between firefox and internet explorer.
For Add and Remove ViewController
var secondViewController :SecondViewController?
// Adding
func add_ViewController() {
let controller = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController")as! SecondViewController
controller.view.frame = self.view.bounds
self.view.addSubview(controller.view)
self.addChild(controller)
controller.didMove(toParent: self)
self.secondViewController = controller
}
// Removing
func remove_ViewController(secondViewController:SecondViewController?) {
if secondViewController != nil {
if self.view.subviews.contains(secondViewController!.view) {
secondViewController!.view.removeFromSuperview()
}
}
}
If you have a full DB dump:
PGPASSWORD="your_pass" psql -h "your_host" -U "your_user" -d "your_database" -f backup.sql
If you have schemas kept separately, however, that won't work. Then you'll need to disable triggers for data insertion, akin to pg_restore --disable-triggers
. You can then use this:
cat database_data_only.gzip | gunzip | PGPASSWORD="your_pass" psql -h "your_host" -U root "your_database" -c 'SET session_replication_role = replica;' -f /dev/stdin
On a side note, it is a very unfortunate downside of postgres, I think. The default way of creating a dump in pg_dump
is incompatible with pg_restore
. With some additional keys, however, it is. WTF?
Long answer:
Floating-point numbers have three components:
Essentially, this works out to sign * 2^exponent * (1 + fraction)
. The “size”
of the number, it’s exponent, is irrelevant to us, because it only scales the
value of the fraction portion. Knowing that log10(n)
gives the number of
digits of n
,† we can determine the precision of a floating point number
with log10(largest_possible_fraction)
. Because each bit in a float stores 2
possibilities, a binary number of n
bits can store a number up to 2n - 1
(a
total of 2n
values where one of the values is zero). This gets a bit
hairier, because it turns out that floating point numbers are stored with one
less bit of fraction than they can use, because zeroes are represented specially
and all non-zero numbers have at least one non-zero binary bit.‡
Combining this, the digits of precision for a floating point number is
log10(2n)
, where n
is the number of bits of the floating point number’s
fraction. A 32-bit float has 24 bits of fraction for ˜7.22 decimal digits of
precision, and a 64-bit double has 53 bits of fraction for ˜15.95 decimal digits
of precision.
For more on floating point accuracy, you might want to read about the concept of a machine epsilon.
† For n = 1
at least — for other numbers your formula will look more like
?log10(|n|)? + 1
.
‡ “This rule is variously called the leading bit convention, the implicit bit convention, or the hidden bit convention.” (Wikipedia)
Mutex work on blocking critical region, But Semaphore work on count.
This question has been answered already several times, I'll short summary for each of them, an example and insights as of September 2019:
Example: <h1>
tag inside <section>
by default Google Chrome will make smaller than the "expected" size of <h1>
tag. Microsoft Edge on the other hand is making the "expected" size of <h1>
tag. Normalize.css will make it consistent.
Current status: the npm repository shows that normalize.css package has currently more than 500k downloads per week. GitHub stars in the project of the repository are more than 36k.
Example: it would do something like that below:
html, body, div, span, ..., audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
Current status: it's much less popular than Normalize.css, the reset-css package shows it's something around 26k downloads per week. GitHub stars are only 200, as it can be noticed from the project's repository.
Pretty sure nobody answer your question to your exact terms, you want it for dynamic text
var newString = myString.substring( myString.indexOf( "," ) +1, myString.length );
It takes a substring from the first comma, to the end
Try joblib http://pythonhosted.org/joblib/memory.html
from joblib import Memory
memory = Memory(cachedir=cachedir, verbose=0)
@memory.cache
def f(x):
print('Running f(%s)' % x)
return x
For anybody coming here looking for a getTickCount() implementation for iOS, here is mine after putting various sources together.
Previously I had a bug in this code (I divided by 1000000 first) which was causing some quantisation of the output on my iPhone 6 (perhaps this was not an issue on iPhone 4/etc or I just never noticed it). Note that by not performing that division first, there is some risk of overflow if the numerator of the timebase is quite large. If anybody is curious, there is a link with much more information here: https://stackoverflow.com/a/23378064/588476
In light of that information, maybe it is safer to use Apple's function CACurrentMediaTime
!
I also benchmarked the mach_timebase_info
call and it takes approximately 19ns on my iPhone 6, so I removed the (not threadsafe) code which was caching the output of that call.
#include <mach/mach.h>
#include <mach/mach_time.h>
uint64_t getTickCount(void)
{
mach_timebase_info_data_t sTimebaseInfo;
uint64_t machTime = mach_absolute_time();
// Convert to milliseconds
mach_timebase_info(&sTimebaseInfo);
machTime *= sTimebaseInfo.numer;
machTime /= sTimebaseInfo.denom;
machTime /= 1000000; // convert from nanoseconds to milliseconds
return machTime;
}
Do be aware of the potential risk of overflow depending on the output of the timebase call. I suspect (but do not know) that it might be a constant for each model of iPhone. on my iPhone 6 it was 125/3
.
The solution using CACurrentMediaTime()
is quite trivial:
uint64_t getTickCount(void)
{
double ret = CACurrentMediaTime();
return ret * 1000;
}
I just want to give the solution that I came up with that handles all cases presented in this post that I derived from Vasek and devconsole. This solution also handles the special case when the phone is rotated more than once while fragments aren't visible.
Here is were I store the bundle for later use since onCreate and onSaveInstanceState are the only calls that are made when the fragment isn't visible
MyObject myObject;
private Bundle savedState = null;
private boolean createdStateInDestroyView;
private static final String SAVED_BUNDLE_TAG = "saved_bundle";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
savedState = savedInstanceState.getBundle(SAVED_BUNDLE_TAG);
}
}
Since destroyView isn't called in the special rotation situation we can be certain that if it creates the state we should use it.
@Override
public void onDestroyView() {
super.onDestroyView();
savedState = saveState();
createdStateInDestroyView = true;
myObject = null;
}
This part would be the same.
private Bundle saveState() {
Bundle state = new Bundle();
state.putSerializable(SAVED_BUNDLE_TAG, myObject);
return state;
}
Now here is the tricky part. In my onActivityCreated method I instantiate the "myObject" variable but the rotation happens onActivity and onCreateView don't get called. Therefor, myObject will be null in this situation when the orientation rotates more than once. I get around this by reusing the same bundle that was saved in onCreate as the out going bundle.
@Override
public void onSaveInstanceState(Bundle outState) {
if (myObject == null) {
outState.putBundle(SAVED_BUNDLE_TAG, savedState);
} else {
outState.putBundle(SAVED_BUNDLE_TAG, createdStateInDestroyView ? savedState : saveState());
}
createdStateInDestroyView = false;
super.onSaveInstanceState(outState);
}
Now wherever you want to restore the state just use the savedState bundle
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
if(savedState != null) {
myObject = (MyObject) savedState.getSerializable(SAVED_BUNDLE_TAG);
}
...
}
I had the same issue, but when I ran the following command, it was ok:
php artisan config:cache
import datetime from datetime
now = datetime.now()
print "%0.2d:%0.2d:%0.2d" % (now.hour, now.minute, now.second)
You can do the same with day & month etc.
To rename files, you can use the rename
utility:
brew install rename
For example, to change a search string in all filenames in current directory:
rename -nvs searchword replaceword *
Remove the 'n' parameter to apply the changes.
More info: man rename
Try this:
//using System.Security.Cryptography.X509Certificates;
public static X509Certificate2 selectCert(StoreName store, StoreLocation location, string windowTitle, string windowMsg)
{
X509Certificate2 certSelected = null;
X509Store x509Store = new X509Store(store, location);
x509Store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = x509Store.Certificates;
X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, windowTitle, windowMsg, X509SelectionFlag.SingleSelection);
if (sel.Count > 0)
{
X509Certificate2Enumerator en = sel.GetEnumerator();
en.MoveNext();
certSelected = en.Current;
}
x509Store.Close();
return certSelected;
}
firstDay = DateSerial(Year(DateAdd("m", -1, Now)), Month(DateAdd("m", -1, Now)), 1)
lastDay = DateAdd("d", -1, DateSerial(Year(Now), Month(Now), 1))
This is another way to do it, but I think Remou's version looks cleaner.
The Content-Security-Policy
meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.
I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.
For brevity I won’t write the full tag in each sample. Instead I'll only show the content
property, so a sample that says content="default-src 'self'"
means this:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
1. How can I allow multiple sources?
You can simply list your sources after a directive as a space-separated list:
content="default-src 'self' https://example.com/js/"
Note that there are no quotes around parameters other than the special ones, like 'self'
. Also, there's no colon (:
) after the directive. Just the directive, then a space-separated list of parameters.
Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:
https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js
These, however, would not be valid:
http://example.com/js/file.js
^^^^ wrong protocol
https://example.com/file.js
^^ above the specified path
2. How can I use different directives? What do they each do?
The most common directives are:
default-src
the default policy for loading javascript, images, CSS, fonts, AJAX requests, etcscript-src
defines valid sources for javascript filesstyle-src
defines valid sources for css filesimg-src
defines valid sources for imagesconnect-src
defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400
errorThere are others, but these are the ones you're most likely to need.
3. How can I use multiple directives?
You define all your directives inside one meta-tag by terminating them with a semicolon (;
):
content="default-src 'self' https://example.com/js/; style-src 'self'"
4. How can I handle ports?
Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:
content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"
The above would result in:
https://ajax.googleapis.com:123
^^^^ Not ok, wrong port
https://ajax.googleapis.com - OK
http://example.com/free/stuff/file.js
^^ Not ok, only the port 123 is allowed
http://example.com:123/free/stuff/file.js - OK
As I mentioned, you can also use an asterisk to explicitly allow all ports:
content="default-src example.com:*"
5. How can I handle different protocols?
By default, only standard protocols are allowed. For example to allow WebSockets ws://
you will have to allow it explicitly:
content="default-src 'self'; connect-src ws:; style-src 'self'"
^^^ web Sockets are now allowed on all domains and ports.
6. How can I allow the file protocol file://
?
If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem
parameter:
content="default-src filesystem"
7. How can I use inline scripts and style definitions?
Unless explicitly allowed, you can't use inline style definitions, code inside <script>
tags or in tag properties like onclick
. You allow them like so:
content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"
You'll also have to explicitly allow inline, base64 encoded images:
content="img-src data:"
8. How can I allow eval()
?
I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:
content="script-src 'unsafe-eval'"
9. What exactly does 'self'
mean?
You might take 'self'
to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.
I've used 'self'
in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.
But hang on a minute! Can't I just use content="default-src *"
and be done with it?
No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:
content="default-src * 'unsafe-inline' 'unsafe-eval'"
... but I trust you won’t.
Further reading:
Just another option, if you want to use only a cli interface, just use the define
option of webpack. I add the following script in my package.json
:
"build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"
So I just have to run npm run build-production
.
WARNING:
git clean -f
will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.
Try this and see git clean -f
.
git reset --hard
will not remove untracked files, where as git-clean
will remove any files from the tracked root directory that are not under Git tracking.
Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)
git clean -df
git clean -xdf
CAUTION! This will also delete ignored filesInterestingly, if you're just typing at the python interactive interpreter, you have to follow a function with a blank line. This does not work:
def foo(x):
return x+1
print "last"
although it is perfectly legal python syntax in a file. There are other syntactic differences when typing to the interpreter too, so beware.
In Notepad++ on the Language menu you will find the menu item - 'J' and under this menu item chose the language - JSON.
Once you select the JSON language then you won't have to worry about how to save it. When you save it it will by default save it as .JSON file, you have to just select the location of the file.
Thanks, -Sam
I was using python interpolation and forgot the ending s
character:
a = dict(foo='bar')
print("What comes after foo? %(foo)" % a) # Should be %(foo)s
Watch those typos.
Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
I think the easiest way to think about this variable like input parameter in lambda expression in C#. I.e. $_
is similar to x
in x => Console.WriteLine(x)
anonymous function in C#. Consider following examples:
PowerShell:
1,2,3 | ForEach-Object {Write-Host $_}
Prints:
1
2
3
or
1,2,3 | Where-Object {$_ -gt 1}
Prints:
2
3
And compare this with C# syntax using LINQ:
var list = new List<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));
Prints:
1
2
3
or
list.Where( _ => _ > 1)
.ToList()
.ForEach(s => Console.WriteLine(s));
Prints:
2
3
In Rails 3.2 I am using:
class ApplicationController < ActionController::Base
before_filter :set_p3p
private
# for IE session cookies thru iframe
def set_p3p
headers['P3P'] = 'CP="ALL DSP COR CURa ADMa DEVa OUR IND COM NAV"'
end
end
I got this from: http://dot-net-web-developer-bristol.blogspot.com/2012/04/setting-p3p-header-in-rails-session.html
The solution
svn status | grep ^? | sed 's/? //' | xargs svn add
does not work with whitespaces. Instead one can use
svn status | grep ^? | sed 's/^? //' | xargs -I fn svn add "fn"
(seems like the number of leading blanks is different on my system -- just adjust it).
As already mentioned, creating your own aggregate function is the right thing to do. Here is my concatenation aggregate function (you can find details in French):
CREATE OR REPLACE FUNCTION concat2(text, text) RETURNS text AS '
SELECT CASE WHEN $1 IS NULL OR $1 = \'\' THEN $2
WHEN $2 IS NULL OR $2 = \'\' THEN $1
ELSE $1 || \' / \' || $2
END;
'
LANGUAGE SQL;
CREATE AGGREGATE concatenate (
sfunc = concat2,
basetype = text,
stype = text,
initcond = ''
);
And then use it as:
SELECT company_id, concatenate(employee) AS employees FROM ...
error 'Class' does not name a type
Just in case someone does the same idiotic thing I did ... I was creating a small test program from scratch and I typed Class instead of class (with a small C). I didn't take any notice of the quotes in the error message and spent a little too long not understanding my problem.
My search for a solution brought me here so I guess the same could happen to someone else.
This may work for you. I used it for cleaning folders during deployments for deleting old deployment files.
clean_anyfolder() {
local temp2="$1/**"; //PATH
temp3=( $(ls -d $temp2 -t | grep "`date | awk '{print $2" "$3}'`") )
j=0;
while [ $j -lt ${#temp3[@]} ]
do
echo "to be removed ${temp3[$j]}"
delete_file_or_folder ${temp3[$j]} 0 //DELETE HERE
fi
j=`expr $j + 1`
done
}
You can write a script and then use nohup ./yourscript &
to execute
For example:
vi yourscript
put
#!/bin/bash
script here
you may also need to change permission to run script on server
chmod u+rwx yourscript
finally
nohup ./yourscript &
For those who are new to SOAP
and want a quick explanation and guide, I strongly recommend this awesome medium article.
You can also use node-soap
package, with this simple tutorial.
JavaScript
function validateNumber(evt) {
var e = evt || window.event;
var key = e.keyCode || e.which;
if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
// numbers
key >= 48 && key <= 57 ||
// Numeric keypad
key >= 96 && key <= 105 ||
// Backspace and Tab and Enter
key == 8 || key == 9 || key == 13 ||
// Home and End
key == 35 || key == 36 ||
// left and right arrows
key == 37 || key == 39 ||
// Del and Ins
key == 46 || key == 45) {
// input is VALID
}
else {
// input is INVALID
e.returnValue = false;
if (e.preventDefault) e.preventDefault();
}
}
additional you could add comma, period and minus (,.-)
// comma, period and minus, . on keypad
key == 190 || key == 188 || key == 109 || key == 110 ||
HTML
<input type="text" onkeydown="validateNumber(event);"/ >
You can use the following nginx configuration example:
upstream adminhost {
server adminhostname:8080;
}
server {
listen 80;
location ~ ^/admin/(.*)$ {
proxy_pass http://adminhost/$1$is_args$args;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
July 25, 2019 :
I was facing this issue in Android Studio 3.0.1 :
After checking lots of posts, here is Fix which works:
Go to module build.gradle and within Android block add this script:
splits {
abi {
enable true
reset()
include 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'mips', 'mips64', 'arm64-v8a'
universalApk true
}
}
Simple Solution. Feel free to comment. Thanks.
Basically in the world of IT certifications, you can call yourself just about anything you want as long as you don't step on the toes of a "real" professional organization. For example, you can be a "Microsoft Certified Solution Engineer" on your business card, but if you write the magic phrase "Professional Engineer" (or P. Eng) you're in legal trouble unless you've got that iron ring. I know there's a similar title for "real" architects, which I can't remember, but as long as you don't mention that you can be a "Cisco Certified Network Architect" or similar.
echo "1 2 3 4 5 6" | awk '{ $NF = ""; print $0}'
this one uses awk to print all except the last field
Use console.log(JSON.stringify(result))
to get the JSON in a string format.
EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty
and access the property if it does exist:
var obj = {id : "007", name : "James Bond"};
console.log(obj); // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj)); //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
console.log(obj.id); //007
}
It depends on how do you want to create the thread and available .NET version:
.NET 2.0+:
A) You can create the Thread
object directly. In this case you could use "closure" - declare variable and capture it using lambda-expression:
object result = null;
Thread thread = new System.Threading.Thread(() => {
//Some work...
result = 42; });
thread.Start();
thread.Join();
Console.WriteLine(result);
B) You can use delegates and IAsyncResult
and return value from EndInvoke()
method:
delegate object MyFunc();
...
MyFunc x = new MyFunc(() => {
//Some work...
return 42; });
IAsyncResult asyncResult = x.BeginInvoke(null, null);
object result = x.EndInvoke(asyncResult);
C) You can use BackgroundWorker
class. In this case you could use captured variable (like with Thread
object) or handle RunWorkerCompleted
event:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (s, e) => {
//Some work...
e.Result = 42;
};
worker.RunWorkerCompleted += (s, e) => {
//e.Result "returned" from thread
Console.WriteLine(e.Result);
};
worker.RunWorkerAsync();
.NET 4.0+:
Starting with .NET 4.0 you could use Task Parallel Library and Task
class to start your threads. Generic class Task<TResult>
allows you to get return value from Result
property:
//Main thread will be blocked until task thread finishes
//(because of obtaining the value of the Result property)
int result = Task.Factory.StartNew(() => {
//Some work...
return 42;}).Result;
.NET 4.5+:
Starting with .NET 4.5 you could also use async
/await
keywords to return value from task directly instead of obtaining Result
property:
int result = await Task.Run(() => {
//Some work...
return 42; });
Note: method, which contains the code above shoud be marked with async
keyword.
For many reasons using of Task Parallel Library is preferable way of working with threads.
With less you can set it up like this;
.table tbody tr {
&.error > td { background-color: red !important; }
&.error:hover > td { background-color: yellow !important; }
&.success > td { background-color: green !important; }
&.success:hover > td { background-color: yellow !important; }
...
}
That did the trick for me.
git stash list
to list your stashed changes.
git stash show
to see what n
is in the below commands.
git stash apply
to apply the most recent stash.
git stash apply stash@{n}
to apply an older stash.
https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning
As suggested by Adam Miller in the comments, I'll add another solution.
The MailMessage(String from, String to) constructor accepts a comma separated list of addresses. So if you happen to have already a comma (',') separated list, the usage is as simple as:
MailMessage Msg = new MailMessage(fromMail, addresses);
In this particular case, we can replace the ';' for ',' and still make use of the constructor.
MailMessage Msg = new MailMessage(fromMail, addresses.replace(";", ","));
Whether you prefer this or the accepted answer it's up to you. Arguably the loop makes the intent clearer, but this is shorter and not obscure. But should you already have a comma separated list, I think this is the way to go.
Here is how it worked for me The PATH for jupyter after installing it using pip is located
which pip
/usr/local/bin
so to run the jupyter notebook i just typed in my terminal:
jupyter-notebook
and it worked for me am using parrot os and installed jupyter using pip3
A container exits when its main process exits. Doing something like:
docker run -itd debian
to hold the container open is frankly a hack that should only be used for quick tests and examples. If you just want a container for testing for a few minutes, I would do:
docker run -d debian sleep 300
Which has the advantage that the container will automatically exit if you forget about it. Alternatively, you could put something like this in a while
loop to keep it running forever, or just run an application such as top
. All of these should be easy to do in Kubernetes.
The real question is why would you want to do this? Your container should be providing a service, whose process will keep the container running in the background.
The text color can be changed using,
<span style='color:green'> message/text </span>
Select extract rows from the relation with some condition and Project extract particular number of attribute/column from the relation with or without some condition.
for those stumbling upon this question: the python jsonlines
library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/
You need to give required = false
for name
and password
request parameters as well. That's because, when you provide just the logout
parameter, it actually expects for name
and password
as well as they are still mandatory.
It worked when you just gave name
and password
because logout
wasn't a mandatory parameter thanks to required = false
already given for logout
.
override onReceivedSslError and remove
super.onReceivedSslError(view, handler, error)
And to solve Google security:
setDomStorageEnabled(true);
Full code is:
webView.enableJavaScript();
webView.getSettings().setDomStorageEnabled(true); // Add this
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.setWebViewClient(new WebViewClient(){
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
// DO NOT CALL SUPER METHOD
super.onReceivedSslError(view, handler, error);
}
});
You can use the static
from()
method from the LayoutInflater
class:
LayoutInflater li = LayoutInflater.from(context);
Look at Compare-Object
Compare-Object $a1 $b1 | ForEach-Object { $_.InputObject }
Or if you would like to know where the object belongs to, then look at SideIndicator:
$a1=@(1,2,3,4,5,8)
$b1=@(1,2,3,4,5,6)
Compare-Object $a1 $b1
Here's a simple example in C++11.
#include <mutex> // mutex
#include <iostream> // cout
#include <cstdio> // getchar
#include <thread> // this_thread, yield
#include <future> // async
#include <chrono> // seconds
using namespace std;
mutex _m1;
mutex _m2;
// Deadlock will occur because func12 and func21 acquires the two locks in reverse order
void func12()
{
unique_lock<mutex> l1(_m1);
this_thread::yield(); // hint to reschedule
this_thread::sleep_for( chrono::seconds(1) );
unique_lock<mutex> l2(_m2 );
}
void func21()
{
unique_lock<mutex> l2(_m2);
this_thread::yield(); // hint to reschedule
this_thread::sleep_for( chrono::seconds(1) );
unique_lock<mutex> l1(_m1);
}
int main( int argc, char* argv[] )
{
async(func12);
func21();
cout << "All done!"; // this won't be executed because of deadlock
getchar();
}
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
If the component is an EJB, then, there shouldn't be a problem injecting an EM.
But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.
This is probably the problem.
Here's some options that keep the file self-contained without retastering the image:
div
tags<div style="width:300px; height:200px">
![Image](path/to/image)
</div>
---
title: test
output: html_document
css: test.css
---
## Page with an image {#myImagePage}
![Image](path/to/image)
#myImagePage img {
width: 400px;
height: 200px;
}
If you have more than one image you might need to use the nth-child pseudo-selector for this second option.
I do not have a JDK installed on my machine to verify this, but here's something to get you started with
%CLASSPATH%=C:\Program Files\Java\jdk1.6\bin rem or whatever your path is
START %CLASSPATH%\javac Main.java
START %CLASSPATH%\java Main
Thank you @Razvan who pointed me in the right direction. I was able to get it in one line and I successfully hunted down the imports for Hamcrest 1.3.
the imports:
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
the code:
assertThat( myClass.getMyItems(), contains(
hasProperty("name", is("foo")),
hasProperty("name", is("bar"))
));
Minimum version I've ever used (doesn't check version, just Flash Plugin):
var hasFlash = function() {
return (typeof navigator.plugins == "undefined" || navigator.plugins.length == 0) ? !!(new ActiveXObject("ShockwaveFlash.ShockwaveFlash")) : navigator.plugins["Shockwave Flash"];
};
A lot of answers ask you to use END
, but if that's not working for you, try:
text.delete("1.0", "end-1c")
There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:
$someElement.on('event', function() {
$('#myDiv').addClass('submission-ok').trigger('classChange');
});
// in another js file, far, far away
$('#myDiv').on('classChange', function() {
// do stuff
});
UPDATE
This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver
:
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
mutations.forEach(function(mutation) {_x000D_
if (mutation.attributeName === "class") {_x000D_
var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
console.log("Class attribute changed to:", attributeValue);_x000D_
}_x000D_
});_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
Be aware that the MutationObserver
is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.
'const' is an indication to your code that the identifier will not be reassigned. This is a good article about when to use 'const', 'let' or 'var' https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75#.ukgxpfhao
There are 3 levels of git config; project, global and system.
Create a project specific config, you have to execute this under the project's directory:
$ git config user.name "John Doe"
Create a global config:
$ git config --global user.name "John Doe"
Create a system config:
$ git config --system user.name "John Doe"
And as you may guess, project overrides global and global overrides system.
Note: Project configs are local to just one particular copy/clone of this particular repo, and need to be reapplied if the repo is recloned clean from the remote. It changes a local file that is not sent to the remote with a commit/push.
chart.series[0].setData(data,true);
The setData
method itself will call the redraw method
Make sure the project does not have any errors. Delete the project from workspace(make the workspace a different directory from the git folder) and import again.
Thanks to Karl Knechtel i was able to understand your question. My interpretation:
First question using anonymous function (aka. Lambda function):
s = lambda l: [(l[0]+l[1])/2.] + s(l[1:]) if len(l)>1 else [] #assuming you want result as float
s = lambda l: [(l[0]+l[1])//2] + s(l[1:]) if len(l)>1 else [] #assuming you want floor result
Second question also using anonymous function (aka. Lambda function):
p = lambda l: l[0] + p(l[1:]) if l!=[] else 0
Both questions combined in a single line of code :
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0 #assuming you want result as float
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0 #assuming you want floor result
use the one that fits best your needs
def cube(x):
if 0<=x: return x**(1./3.)
return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))
Here is the full answer for both negative and positive numbers.
>>>
2.0
-2.0
>>>
Or here is a one-liner;
root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)
package com.st.removeduplicate;
public class RemoveDuplicate {
public static void main(String[] args) {
String str1="shushil",str2="";
for(int i=0; i<=str1.length()-1;i++) {
int count=0;
for(int j=0;j<=i;j++) {
if(str1.charAt(i)==str1.charAt(j))
count++;
if(count >1)
break;
}
if(count==1)
str2=str2+str1.charAt(i);
}
System.out.println(str2);
}
}
$("#year").datepicker( {
format: "yyyy",
viewMode: "years",
minViewMode: "years"
}).on('changeDate', function(e){
$(this).datepicker('hide');
});
Just adding for who might need.. Don't forget to alter the table!
ALTER TABLE table_name ADD FULLTEXT(column_name);
To make it short:
Node.js is well suited for applications that have a lot of concurrent connections and each request only needs very few CPU cycles, because the event loop (with all the other clients) is blocked during execution of a function.
A good article about the event loop in Node.js is Mixu's tech blog: Understanding the node.js event loop.
Git add .
Git status //Check file that being modified
// git reset HEAD --- replace to which file you want to ignore
git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!
git commit -m ''
git push
Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :
-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440
The return
exits the current function, but the iterations keeps on, so you get the "next" item that skips the if
and alerts the 4...
If you need to stop the looping, you should just use a plain for
loop like so:
$('button').click(function () {
var arr = [1, 2, 3, 4, 5];
for(var i = 0; i < arr.length; i++) {
var n = arr[i];
if (n == 3) {
break;
}
alert(n);
})
})
You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp
NOTE: HSSFDateUtil is deprecated
If you know which cell i.e. column position say 0 in each row is going to be a date, you can go for
row.getCell(0).getDateCellValue()
directly.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()
UPDATE: Here is an example - you can apply this in your switch case code above. I am checking and printing the Numeric as well as Date value. In this case the first column in my sheet has dates, hence I use row.getCell(0).
You can use the if (HSSFDateUtil.isCellDateFormatted ..
code block directly in your switch case.
if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getNumericCellValue());
if (HSSFDateUtil.isCellDateFormatted(row.getCell(0))) {
System.out.println ("Row No.: " + row.getRowNum ()+ " " +
row.getCell(0).getDateCellValue());
}
}
The output is
Row No.: 0 39281.0
Row No.: 0 Wed Jul 18 00:00:00 IST 2007
Row No.: 1 39491.0
Row No.: 1 Wed Feb 13 00:00:00 IST 2008
Row No.: 2 39311.0
Row No.: 2 Fri Aug 17 00:00:00 IST 2007
[In Python3]
Let's say you want to handle an IndexError
and print the traceback, you can do the following:
from traceback import print_tb
empty_list = []
try:
x = empty_list[100]
except IndexError as index_error:
print_tb(index_error.__traceback__)
Note: You can use the format_tb
function instead of print_tb
to get the traceback as a string for logging purposes.
Hope this helps.
>>> command = "echo a; echo b"
>>> shlex.split(command);
['echo', 'a; echo', 'b']
so, the problem is shlex module do not handle ";"
Another real world example using a list
an extract for a template for php.ini
{% if 'cli/php.ini' in item.d %}
max_execution_time = 0
memory_limit = 1024M
{% else %}
max_execution_time = 300
memory_limit = 512M
{% endif %}
This is the var
php_templates:
- { s: 'php.ini.j2', d: "/etc/php/{{php_version}}/apache2/php.ini" }
- { s: 'php.ini.j2', d: "/etc/php/{{php_version}}/cli/php.ini" }
Then i deploy with this
- name: push templated files
template:
src: "{{item.s}}"
dest: "{{item.d}}"
mode: "{{item.m | default(0644) }}"
owner: "{{item.o | default('root') }}"
group: "{{item.g | default('root') }}"
backup: yes
with_items: "{{php_templates}}"
In my case it was a simple bug in the code, using a variable before it was created. Worth checking that out before trying the above solutions. Why I got this particular error message, Lord knows.
Old thread, but still a valid concern. I noticed some good responses about security, and avoiding use of 'security through obscurity', but the actual technical methods given were not sufficient in my eyes. Things I must say before I contribute my method:
That all being said, there are two great ways to have auto-signin on your system.
First, the cheap, easy way that puts it all on someone else. If you make your site support logging in with, say, your google+ account, you probably have a streamlined google+ button that will log the user in if they are already signed into google (I did that here to answer this question, as I am always signed into google). If you want the user automatically signed in if they are already signed in with a trusted and supported authenticator, and checked the box to do so, have your client-side scripts perform the code behind the corresponding 'sign-in with' button before loading, just be sure to have the server store a unique ID in an auto-signin table that has the username, session ID, and the authenticator used for the user. Since these sign-in methods use AJAX, you are waiting for a response anyway, and that response is either a validated response or a rejection. If you get a validated response, use it as normal, then continue loading the logged in user as normal. Otherwise, the login failed, but don't tell the user, just continue as not logged in, they will notice. This is to prevent an attacker who stole cookies (or forged them in an attempt to escalate privileges) from learning that the user auto-signs into the site.
This is cheap, and might also be considered dirty by some because it tries to validate your potentially already signed in self with places like Google and Facebook, without even telling you. It should, however, not be used on users who have not asked to auto-signin your site, and this particular method is only for external authentication, like with Google+ or FB.
Because an external authenticator was used to tell the server behind the scenes whether or not a user was validated, an attacker cannot obtain anything other than a unique ID, which is useless on its own. I'll elaborate:
No matter what, even if an attacker uses an ID that does not exist, the attempt should fail on all attempts except when a validated response is received.
This method can and should be used in conjunction with your internal authenticator for those who sign into your site using an external authenticator.
=========
Now, for your very own authenticator system that can auto-signin users, this is how I do it:
DB has a few tables:
TABLE users:
UID - auto increment, PK
username - varchar(255), unique, indexed, NOT NULL
password_hash - varchar(255), NOT NULL
...
Note that the username is capable of being 255 characters long. I have my server program limit usernames in my system to 32 characters, but external authenticators might have usernames with their @domain.tld be larger than that, so I just support the maximum length of an email address for maximum compatibility.
TABLE sessions:
session_id - varchar(?), PK
session_token - varchar(?), NOT NULL
session_data - MediumText, NOT NULL
Note that there is no user field in this table, because the username, when logged in, is in the session data, and the program does not allow null data. The session_id and the session_token can be generated using random md5 hashes, sha1/128/256 hashes, datetime stamps with random strings added to them then hashed, or whatever you would like, but the entropy of your output should remain as high as tolerable to mitigate brute-force attacks from even getting off the ground, and all hashes generated by your session class should be checked for matches in the sessions table prior to attempting to add them.
TABLE autologin:
UID - auto increment, PK
username - varchar(255), NOT NULL, allow duplicates
hostname - varchar(255), NOT NULL, allow duplicates
mac_address - char(23), NOT NULL, unique
token - varchar(?), NOT NULL, allow duplicates
expires - datetime code
MAC addresses by their nature are supposed to be UNIQUE, therefore it makes sense that each entry has a unique value. Hostnames, on the other hand, could be duplicated on separate networks legitimately. How many people use "Home-PC" as one of their computer names? The username is taken from the session data by the server backend, so manipulating it is impossible. As for the token, the same method to generate session tokens for pages should be used to generate tokens in cookies for the user auto-signin. Lastly, the datetime code is added for when the user would need to revalidate their credentials. Either update this datetime on user login keeping it within a few days, or force it to expire regardless of last login keeping it only for a month or so, whichever your design dictates.
This prevents someone from systematically spoofing the MAC and hostname for a user they know auto-signs in. NEVER have the user keep a cookie with their password, clear text or otherwise. Have the token be regenerated on each page navigation, just as you would the session token. This massively reduces the likelihood that an attacker could obtain a valid token cookie and use it to login. Some people will try to say that an attacker could steal the cookies from the victim and do a session replay attack to login. If an attacker could steal the cookies (which is possible), they would certainly have compromised the entire device, meaning they could just use the device to login anyway, which defeats the purpose of stealing cookies entirely. As long as your site runs over HTTPS (which it should when dealing with passwords, CC numbers, or other login systems), you have afforded all the protection to the user that you can within a browser.
One thing to keep in mind: session data should not expire if you use auto-signin. You can expire the ability to continue the session falsely, but validating into the system should resume the session data if it is persistent data that is expected to continue between sessions. If you want both persistent AND non-persistent session data, use another table for persistent session data with the username as the PK, and have the server retrieve it like it would the normal session data, just use another variable.
Once a login has been achieved in this way, the server should still validate the session. This is where you can code expectations for stolen or compromised systems; patterns and other expected results of logins to session data can often lead to conclusions that a system was hijacked or cookies were forged in order to gain access. This is where your ISS Tech can put rules that would trigger an account lockdown or auto-removal of a user from the auto-signin system, keeping attackers out long enough for the user to determine how the attacker succeeded and how to cut them off.
As a closing note, be sure that any recovery attempt, password changes, or login failures past the threshold result in auto-signin being disabled until the user validates properly and acknowledges this has occurred.
I apologize if anyone was expecting code to be given out in my answer, that's not going to happen here. I will say that I use PHP, jQuery, and AJAX to run my sites, and I NEVER use Windows as a server... ever.
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
just to not forget the format
method
String s = String.format("%s%s%s%s%s", a, b, c, d, e);
(%1.1s%1.1s%1.1s%1.1s%1.1s
if you only want the first digit of each number...)
If you are doing it with Django, you can just pass the function with the context:
context = {
'title':'My title',
'str': str,
}
...
return render(request, 'index.html', context)
Now you will be able to use the str
function in jinja2 template
you can also use:
<?php
ob_start();
echo "some text";
echo "\n";
// you can also use:
?>
some text can be also written here, or maybe HTML:
<div>whatever<\div>
<?php
echo "you can basically write whatever you want";
// and then:
$long_text = ob_get_clean();
You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.
As I mentioned in the comment, having to use the dot()
function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.
Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @
infix-operator for matrix multiplication, thanks to pep 465.
Edit: Regarding your comment:
Yes. The whole of numpy is based on arrays.
Yes. linalg.norm(v)
is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.
To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.
An example in ipython:
In [1]: import math
In [2]: import numpy as np
In [3]: a = np.array([4,2,7])
In [4]: np.linalg.norm(a)
Out[4]: 8.3066238629180749
In [5]: math.sqrt(sum([n**2 for n in a]))
Out[5]: 8.306623862918075
In [6]: b = a/np.linalg.norm(a)
In [7]: np.linalg.norm(b)
Out[7]: 1.0
Note that In [5]
is an alternative way to calculate the length. In [6]
shows normalizing the vector.
Another intuitive solution could be:
class Post
{
public $title;
public $date;
}
$posts = array();
$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';
$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';
foreach ($posts as $post) {
echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}
Enable compression via .htaccess
For most people reading this, compression is enabled by adding some code to a file called .htaccess on their web host/server. This means going to the file manager (or wherever you go to add or upload files) on your webhost.
The .htaccess file controls many important things for your site.
The code below should be added to your .htaccess file...
<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>
Save the .htaccess file and then refresh your webpage.
Check to see if your compression is working using the Gzip compression tool.
You can use the already mentioned built in Responsive Design Mode (via dev tools) for setting customised screen sizes together with the Random Agent Spoofer Plugin to modify your headers to simulate you are using Mobile, Tablet etc. Many websites specify their content according to these identified headers.
As dev tools you can use the built in Developer Tools (Ctrl + Shift + I or Cmd + Shift + I for Mac) which have become quite similar to Chrome dev tools by now.
Use the hex code for a non-breaking space. Something like this:
.breadcrumbs a:before {
content: '>\00a0';
}
For Eclipse in Macbook it is just 2 click process:
<div class="content scrollable" ref="msgContainer">
<!-- content -->
</div>
data() {
return {
count: 5
};
},
watch: {
count: function() {
this.$nextTick(function() {
var container = this.$refs.msgContainer;
container.scrollTop = container.scrollHeight + 120;
});
}
}
.scrollable {
overflow: hidden;
overflow-y: scroll;
height: calc(100vh - 20px);
}
Your code requires that the Dog
class has overridden the toString()
method so that it knows how to print itself out. Otherwise, your code looks correct.
Fake IE10 to install Visual Studio 2013
Visual Studio 2013 requires Internet Explorer 10. If you try to install it on Windows 7 with IE8 you get the following error This version of Visual Studio requires Internet Explorer 10”. The value that the VS 2013 installer checks is svcVersion in the
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer
key on 32-bit Windows andHKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer
on 64-bit Windows. Any value >= 10.0.0.0 makes the installer happy.
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"
There is a rule in Python programming called "it is Easier to Ask for Forgiveness than for Permission" (in short: EAFP). It means that you should catch exceptions instead of checking values for validity.
Thus, try the following:
try:
qByUser = byUsrUrlObj.read()
qUserData = json.loads(qByUser).decode('utf-8')
questionSubjs = qUserData["all"]["questions"]
except ValueError: # includes simplejson.decoder.JSONDecodeError
print 'Decoding JSON has failed'
EDIT: Since simplejson.decoder.JSONDecodeError
actually inherits from ValueError
(proof here), I simplified the catch statement by just using ValueError
.
Just copy an image into your res/drawable
folder and use
imageView.setImageResource(R.drawable.my_image);
The variety of answers can cause a little confusion. We have
setBackgroundResource()
setBackgroundDrawable()
setBackground()
setImageResource()
setImageDrawable()
setImageBitmap()
The methods with Background
in their name all belong to the View
class, not to ImageView
specifically. But since ImageView
inherits from View
you can use them, too. The methods with Image
in their name belong specifically to ImageView
.
The View
methods all do the same thing as each other (though setBackgroundDrawable()
is deprecated), so we will just focus on setBackgroundResource()
. Similarly, the ImageView
methods all do the same thing, so we will just focus on setImageResource()
. The only difference between the methods is they type of parameter you pass in.
Here is a FrameLayout
that contains an ImageView
. The ImageView
initially doesn't have any image in it. (I only added the FrameLayout
so that I could put a border around it. That way you can see the edge of the ImageView
.)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="250dp"
android:layout_height="250dp"
android:background="@drawable/border"
android:layout_centerInParent="true">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
</RelativeLayout>
Below we will compare the different methods.
If you use ImageView's setImageResource()
, then the image keeps its aspect ratio and is resized to fit. Here are two different image examples.
imageView.setImageResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);
Using View's setBackgroundResource()
, on the other hand, causes the image resource to be stretched to fill the view.
imageView.setBackgroundResource(R.drawable.sky);
imageView.setBackgroundResource(R.drawable.balloons);
The View's background image and the ImageView's image are drawn separately, so you can set them both.
imageView.setBackgroundResource(R.drawable.sky);
imageView.setImageResource(R.drawable.balloons);
Following sample code works for me. Not sure if it directly relates to this question, but hope it helps in some other cases.
a = ''.join(map(lambda x: str(x*2) if x%2==0 else "", range(10)))
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
a = 5
makes the variable name a
to refer to the integer 5. Later, a = "hello"
makes the variable name a
to refer to a string containing "hello". Static typed languages would have you declare int a
and then a = 5
, but assigning a = "hello"
would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a
refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.a = "5"
(the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5
to get "hello5"
.Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
You have most of the code…
CURLOPT_HTTPHEADER
for curl_setopt()
takes an array with each header as an element. You have one element with multiple headers.
You also need to add the Authorization header to your $header
array.
$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';
Another way this could be accomplished is by using the Start-Transcript
and Stop-Transcript
commands, respectively before and after command execution. This would capture the entire session including commands.
For this particular case Out-File
is probably your best bet though.
A good way to create Public/Global variables is to treat the Form like a class object and declare properties and use Public Property Get [variable] to access property/method. Also you might need to reference or pass a Reference to the instantiated Form module. You will get errors if you call methods to forms/reports that are closed.
Example: pass Me.Form.Module.Parent into sub/function not inside form.
Option Compare Database
Option Explicit
''***********************************''
' Name: Date: Created Date Author: Name
' Current Version: 1.0
' Called by:
''***********************************''
' Notes: Explain Who what when why...
' This code Example requires properties to be filled in
''***********************************''
' Global Variables
Public GlobalData As Variant
''***********************************''
' Private Variables
Private ObjectReference As Object
Private ExampleVariable As Variant
Private ExampleData As Variant
''***********************************''
' Public properties
Public Property Get ObjectVariable() As Object
Set ObjectVariable = ObjectReference
End Property
Public Property Get Variable1() As Variant
'Recommend using variants to avoid data errors
Variable1 = ExampleVariable
End property
''***********************************''
' Public Functions that return values
Public Function DataReturn (Input As Variant) As Variant
DataReturn = ExampleData + Input
End Function
''***********************************''
' Public Sub Routines
Public Sub GlobalMethod()
'call local Functions/Subs outside of form
Me.Form.Refresh
End Sub
''***********************************''
' Private Functions/Subs used not visible outside
''***********************************''
End Code
So in the other module you would be able to access:
Public Sub Method1(objForm as Object)
'read/write data value
objForm.GlobalData
'Get object reference (need to add Public Property Set to change reference object)
objForm.ObjectVariable
'read only (needs Public property Let to change value)
objForm.Variable1
'Gets result of function with input
objForm.DataReturn([Input])
'runs sub/function from outside of normal scope
objForm.GlobalMethod
End Sub
If you use Late Binding like I do always check for Null values and objects that are Nothing before attempting to do any processing.
My sugestion in postgresql
SELECT cpf || ';' || nome || ';' || telefone
FROM (
SELECT cpf
,nome
,STRING_AGG(CONCAT_WS( ';' , DDD_1, TELEFONE_1),';') AS telefone
FROM (
SELECT DISTINCT *
FROM temp_bd
ORDER BY cpf DESC ) AS y
GROUP BY 1,2 ) AS x
In my case, the problem was the protocol. I was trying to call a script url with http
instead of https
.
There are already answers here, but here's my pure JS implementation. I'm not sure if it's optimal, but it sure is transparent, readable, and simple.
// Does array a contain elements of array b?
const contains = (a, b) => new Set([...a, ...b]).size === a.length
const isEqualSet = (a, b) => contains(a, b) && contains(b, a)
The rationale in contains()
is that if a
does contain all the elements of b
, then putting them into the same set would not change the size.
For example, if const a = [1,2,3,4]
and const b = [1,2]
, then new Set([...a, ...b]) === {1,2,3,4}
. As you can see, the resulting set has the same elements as a
.
From there, to make it more concise, we can boil it down to the following:
const isEqualSet = (a, b) => {
const unionSize = new Set([...a, ...b])
return unionSize === a.length && unionSize === b.length
}
If you are happy to run a batch file along with a couple of tiny helper programs, a complete solution is posted here:
How can a batch file run a program and set the position and size of the window? - Stack Overflow (asked: May 1, 2012)
In my case, it was not using a DataTemplate for the ItemsControl.
Old:
<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
<StackPanel Orientation="Horizontal">
<TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
<Label Content="{Binding Path=Property2}"/>
</StackPanel>
</ItemsControl>
New:
<ItemsControl Width="243" ItemsSource="{Binding List, Mode=TwoWay}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Width="25" Margin="0,0,5,0" Text="{Binding Path=Property1}"/>
<Label Content="{Binding Path=Property2}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Got the same problem, non of the answers worked for me. After a lot of debugging I found out that the size of one image was smaller than 32
. This leads to a broken array with wrong dimensions and the above mentioned error.
To solve the problem, make sure that all images have the correct dimensions.
This also works:
db.Account.find().sort('UserName', -1)
db.Account.find().sort('UserName', 1)
I'm using this in my code, please comment if i'm doing something wrong here, thanks.
//
syntaxregex.test(string)
, not string.test(regex)
So
jQuery(function () {
$(".mail").keyup(function () {
var VAL = this.value;
var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');
if (email.test(VAL)) {
alert('Great, you entered an E-Mail-address');
}
});
});
Unless you plan on creating your own drop down list (and not using a standard library drop down list), you are stuck. The DDL control's look is going to be based upon the system you are running and/or the browser that is rendering the output.
You have to put:
<html ng-app="urlApp" ng-controller="urlCtrl">
This way the angular function can access into "window" object
In swift,
let myLabel : UILabel!
To make your text of your Label to fit to screen and it's on the top
myLabel.sizeToFit()
To make your font of label to fit to the width of screen or specific width size.
myLabel.adjustsFontSizeToFitWidth = YES
and some textAlignment for label :
myLabel.textAlignment = .center
myLabel.textAlignment = .left
myLabel.textAlignment = .right
myLabel.textAlignment = .Natural
myLabel.textAlignment = .Justified
This thread might be dead, but StyledMarker is available for API v3. Just bind the color change you want to the correct DOM event using the addDomListener() method. This example is pretty close to what you want to do. If you look at the page source, change:
google.maps.event.addDomListener(document.getElementById("changeButton"),"click",function() {
styleIcon.set("color","#00ff00");
styleIcon.set("text","Go");
});
to something like:
google.maps.event.addDomListener("mouseover",function() {
styleIcon.set("color","#00ff00");
styleIcon.set("text","Go");
});
That should be enough to get you moving along.
The Wikipedia page on DOM Events will also help you target the event that you want to capture on the client-side.
Good luck (if you still need it)
try this:
#include <iostream>
using namespace std;
int main()
{
int positiveInteger;
int startingNumber = 1;
cout << "Please input an integer upto 100." << endl;
cin >> positiveInteger;
int result = 0;
for (int i=startingNumber; i <= positiveInteger; i++)
{
result += i;
cout << result;
}
cout << result;
return 0;
}