Jdk 9 and 10 solution
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<debug>true</debug>
</configuration>
<dependencies>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>6.2</version>
</dependency>
</dependencies>
</plugin>
and make sure your maven is pointing to JDK 10 or 9. mvn -v
Apache Maven 3.5.3 (3383c37e1f9e9b3bc3df5050c29c8aff9f295297; 2018-02-24T14:49:05-05:00)
Maven home: C:\devplay\apache-maven-3.5.3\bin\..
Java version: 10.0.1, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk-10.0.1
Default locale: en_US, platform encoding: Cp1252
OS name: "windows 10", version: "10.0", arch: "amd64", family: "windows"
A bunch of great answers in this thread, but none quite matched my needs. I have a tabbed app with navigation controllers in each tab, and one view needed to rotate, while the others needed to be locked in portrait. The navigation controller wasn't resizing it's subviews properly, for some reason. Found a solution (in Swift 3) by combining with this answer, and the layout issues disappeared. Create the struct as suggest by @bmjohns:
import UIKit
struct OrientationLock {
static func lock(to orientation: UIInterfaceOrientationMask) {
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.orientationLock = orientation
}
}
static func lock(to orientation: UIInterfaceOrientationMask, andRotateTo rotateOrientation: UIInterfaceOrientation) {
self.lock(to: orientation)
UIDevice.current.setValue(rotateOrientation.rawValue, forKey: "orientation")
}
}
Then subclass UITabBarController:
import UIKit
class TabBarController: UITabBarController, UITabBarControllerDelegate {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.delegate = self
}
func tabBarControllerSupportedInterfaceOrientations(_ tabBarController: UITabBarController) -> UIInterfaceOrientationMask {
if tabBarController.selectedViewController is MyViewControllerNotInANavigationControllerThatShouldRotate {
return .allButUpsideDown
} else if let navController = tabBarController.selectedViewController as? UINavigationController, navController.topViewController is MyViewControllerInANavControllerThatShouldRotate {
return .allButUpsideDown
} else {
//Lock view that should not be able to rotate
return .portrait
}
}
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
if viewController is MyViewControllerNotInANavigationControllerThatShouldRotate {
OrientationLock.lock(to: .allButUpsideDown)
} else if let navController = viewController as? UINavigationController, navController.topViewController is MyViewControllerInANavigationControllerThatShouldRotate {
OrientationLock.lock(to: .allButUpsideDown)
} else {
//Lock orientation and rotate to desired orientation
OrientationLock.lock(to: .portrait, andRotateTo: .portrait)
}
return true
}
}
Don't forget to change the class of the TabBarController in the storyboard to the newly created subclass.
To add new ViewController
once you have have an existing ViewController
, follow below step:
Click on background of Main.storyboard
.
Search and select ViewController
from object library at the
utility window.
Drag and drop it in background to create a new ViewController
.
There is a new one: http://hayatbiralem.com/blog/2015/05/15/responsive-bootstrap-tabs/
And also Codepen sample available here: http://codepen.io/hayatbiralem/pen/KpzjOL
No needs plugin. It uses just a little css and jquery.
Here's a sample tabs markup:
<ul class="nav nav-tabs nav-tabs-responsive">
<li class="active">
<a href="#tab1" data-toggle="tab">
<span class="text">Tab 1</span>
</a>
</li>
<li class="next">
<a href="#tab2" data-toggle="tab">
<span class="text">Tab 2</span>
</a>
</li>
<li>
<a href="#tab3" data-toggle="tab">
<span class="text">Tab 3</span>
</a>
</li>
...
</ul>
.. and jQuery codes are also here:
(function($) {
'use strict';
$(document).on('show.bs.tab', '.nav-tabs-responsive [data-toggle="tab"]', function(e) {
var $target = $(e.target);
var $tabs = $target.closest('.nav-tabs-responsive');
var $current = $target.closest('li');
var $parent = $current.closest('li.dropdown');
$current = $parent.length > 0 ? $parent : $current;
var $next = $current.next();
var $prev = $current.prev();
var updateDropdownMenu = function($el, position){
$el
.find('.dropdown-menu')
.removeClass('pull-xs-left pull-xs-center pull-xs-right')
.addClass( 'pull-xs-' + position );
};
$tabs.find('>li').removeClass('next prev');
$prev.addClass('prev');
$next.addClass('next');
updateDropdownMenu( $prev, 'left' );
updateDropdownMenu( $current, 'center' );
updateDropdownMenu( $next, 'right' );
});
})(jQuery);
Seems like this thread is very popular and it will be sad not to mention here that there is an alternative way - ViewModel First Navigation
. Most of the MVVM frameworks out there using it, however if you want to understand what it is about, continue reading.
All the official Xamarin.Forms documentation is demonstrating a simple, yet slightly not MVVM pure solution. That is because the Page
(View) should know nothing about the ViewModel
and vice versa. Here is a great example of this violation:
// C# version
public partial class MyPage : ContentPage
{
public MyPage()
{
InitializeComponent();
// Violation
this.BindingContext = new MyViewModel();
}
}
// XAML version
<?xml version="1.0" encoding="utf-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewmodels="clr-namespace:MyApp.ViewModel"
x:Class="MyApp.Views.MyPage">
<ContentPage.BindingContext>
<!-- Violation -->
<viewmodels:MyViewModel />
</ContentPage.BindingContext>
</ContentPage>
If you have a 2 pages application this approach might be good for you. However if you are working on a big enterprise solution you better go with a ViewModel First Navigation
approach. It is slightly more complicated but much cleaner approach that allow you to navigate between ViewModels
instead of navigation between Pages
(Views). One of the advantages beside clear separation of concerns is that you could easily pass parameters to the next ViewModel
or execute an async initialization code right after navigation. Now to details.
(I will try to simplify all the code examples as much as possible).
1. First of all we need a place where we could register all our objects and optionally define their lifetime. For this matter we can use an IOC container, you can choose one yourself. In this example I will use Autofac(it is one of the fastest available). We can keep a reference to it in the App
so it will be available globally (not a good idea, but needed for simplification):
public class DependencyResolver
{
static IContainer container;
public DependencyResolver(params Module[] modules)
{
var builder = new ContainerBuilder();
if (modules != null)
foreach (var module in modules)
builder.RegisterModule(module);
container = builder.Build();
}
public T Resolve<T>() => container.Resolve<T>();
public object Resolve(Type type) => container.Resolve(type);
}
public partial class App : Application
{
public DependencyResolver DependencyResolver { get; }
// Pass here platform specific dependencies
public App(Module platformIocModule)
{
InitializeComponent();
DependencyResolver = new DependencyResolver(platformIocModule, new IocModule());
MainPage = new WelcomeView();
}
/* The rest of the code ... */
}
2.We will need an object responsible for retrieving a Page
(View) for a specific ViewModel
and vice versa. The second case might be useful in case of setting the root/main page of the app. For that we should agree on a simple convention that all the ViewModels
should be in ViewModels
directory and Pages
(Views) should be in the Views
directory. In other words ViewModels
should live in [MyApp].ViewModels
namespace and Pages
(Views) in [MyApp].Views
namespace. In addition to that we should agree that WelcomeView
(Page) should have a WelcomeViewModel
and etc. Here is a code example of a mapper:
public class TypeMapperService
{
public Type MapViewModelToView(Type viewModelType)
{
var viewName = viewModelType.FullName.Replace("Model", string.Empty);
var viewAssemblyName = GetTypeAssemblyName(viewModelType);
var viewTypeName = GenerateTypeName("{0}, {1}", viewName, viewAssemblyName);
return Type.GetType(viewTypeName);
}
public Type MapViewToViewModel(Type viewType)
{
var viewModelName = viewType.FullName.Replace(".Views.", ".ViewModels.");
var viewModelAssemblyName = GetTypeAssemblyName(viewType);
var viewTypeModelName = GenerateTypeName("{0}Model, {1}", viewModelName, viewModelAssemblyName);
return Type.GetType(viewTypeModelName);
}
string GetTypeAssemblyName(Type type) => type.GetTypeInfo().Assembly.FullName;
string GenerateTypeName(string format, string typeName, string assemblyName) =>
string.Format(CultureInfo.InvariantCulture, format, typeName, assemblyName);
}
3.For the case of setting a root page we will need sort of ViewModelLocator
that will set the BindingContext
automatically:
public static class ViewModelLocator
{
public static readonly BindableProperty AutoWireViewModelProperty =
BindableProperty.CreateAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), default(bool), propertyChanged: OnAutoWireViewModelChanged);
public static bool GetAutoWireViewModel(BindableObject bindable) =>
(bool)bindable.GetValue(AutoWireViewModelProperty);
public static void SetAutoWireViewModel(BindableObject bindable, bool value) =>
bindable.SetValue(AutoWireViewModelProperty, value);
static ITypeMapperService mapper = (Application.Current as App).DependencyResolver.Resolve<ITypeMapperService>();
static void OnAutoWireViewModelChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as Element;
var viewType = view.GetType();
var viewModelType = mapper.MapViewToViewModel(viewType);
var viewModel = (Application.Current as App).DependencyResolver.Resolve(viewModelType);
view.BindingContext = viewModel;
}
}
// Usage example
<?xml version="1.0" encoding="utf-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewmodels="clr-namespace:MyApp.ViewModel"
viewmodels:ViewModelLocator.AutoWireViewModel="true"
x:Class="MyApp.Views.MyPage">
</ContentPage>
4.Finally we will need a NavigationService
that will support ViewModel First Navigation
approach:
public class NavigationService
{
TypeMapperService mapperService { get; }
public NavigationService(TypeMapperService mapperService)
{
this.mapperService = mapperService;
}
protected Page CreatePage(Type viewModelType)
{
Type pageType = mapperService.MapViewModelToView(viewModelType);
if (pageType == null)
{
throw new Exception($"Cannot locate page type for {viewModelType}");
}
return Activator.CreateInstance(pageType) as Page;
}
protected Page GetCurrentPage()
{
var mainPage = Application.Current.MainPage;
if (mainPage is MasterDetailPage)
{
return ((MasterDetailPage)mainPage).Detail;
}
// TabbedPage : MultiPage<Page>
// CarouselPage : MultiPage<ContentPage>
if (mainPage is TabbedPage || mainPage is CarouselPage)
{
return ((MultiPage<Page>)mainPage).CurrentPage;
}
return mainPage;
}
public Task PushAsync(Page page, bool animated = true)
{
var navigationPage = Application.Current.MainPage as NavigationPage;
return navigationPage.PushAsync(page, animated);
}
public Task PopAsync(bool animated = true)
{
var mainPage = Application.Current.MainPage as NavigationPage;
return mainPage.Navigation.PopAsync(animated);
}
public Task PushModalAsync<TViewModel>(object parameter = null, bool animated = true) where TViewModel : BaseViewModel =>
InternalPushModalAsync(typeof(TViewModel), animated, parameter);
public Task PopModalAsync(bool animated = true)
{
var mainPage = GetCurrentPage();
if (mainPage != null)
return mainPage.Navigation.PopModalAsync(animated);
throw new Exception("Current page is null.");
}
async Task InternalPushModalAsync(Type viewModelType, bool animated, object parameter)
{
var page = CreatePage(viewModelType);
var currentNavigationPage = GetCurrentPage();
if (currentNavigationPage != null)
{
await currentNavigationPage.Navigation.PushModalAsync(page, animated);
}
else
{
throw new Exception("Current page is null.");
}
await (page.BindingContext as BaseViewModel).InitializeAsync(parameter);
}
}
As you may see there is a BaseViewModel
- abstract base class for all the ViewModels
where you can define methods like InitializeAsync
that will get executed right after the navigation. And here is an example of navigation:
public class WelcomeViewModel : BaseViewModel
{
public ICommand NewGameCmd { get; }
public ICommand TopScoreCmd { get; }
public ICommand AboutCmd { get; }
public WelcomeViewModel(INavigationService navigation) : base(navigation)
{
NewGameCmd = new Command(async () => await Navigation.PushModalAsync<GameViewModel>());
TopScoreCmd = new Command(async () => await navigation.PushModalAsync<TopScoreViewModel>());
AboutCmd = new Command(async () => await navigation.PushModalAsync<AboutViewModel>());
}
}
As you understand this approach is more complicated, harder to debug and might be confusing. However there are many advantages plus you actually don't have to implement it yourself since most of the MVVM frameworks support it out of the box. The code example that is demonstrated here is available on github.
There are plenty of good articles about ViewModel First Navigation
approach and there is a free Enterprise Application Patterns using Xamarin.Forms eBook which is explaining this and many other interesting topics in detail.
The minimal-ui viewport property is no longer supported in iOS 8. However, the minimal-ui itself is not gone. User can enter the minimal-ui with a "touch-drag down" gesture.
There are several pre-conditions and obstacles to manage the view state, e.g. for minimal-ui to work, there has to be enough content to enable user to scroll; for minimal-ui to persist, window scroll must be offset on page load and after orientation change. However, there is no way of calculating the dimensions of the minimal-ui using the screen
variable, and thus no way of telling when user is in the minimal-ui in advance.
These observations is a result of research as part of developing Brim – view manager for iOS 8. The end implementation works in the following way:
When page is loaded, Brim will create a treadmill element. Treadmill element is used to give user space to scroll. Presence of the treadmill element ensures that user can enter the minimal-ui view and that it continues to persist if user reloads the page or changes device orientation. It is invisible to the user the entire time. This element has ID
brim-treadmill
.Upon loading the page or after changing the orientation, Brim is using Scream to detect if page is in the minimal-ui view (page that has been previously in minimal-ui and has been reloaded will remain in the minimal-ui if content height is greater than the viewport height).
When page is in the minimal-ui, Brim will disable scrolling of the document (it does this in a safe way that does not affect the contents of the main element). Disabling document scrolling prevents accidentally leaving the minimal-ui when scrolling upwards. As per the original iOS 7.1 spec, tapping the top bar brings back the rest of the chrome.
The end result looks like this:
For the sake of documentation, and in case you prefer to write your own implementation, it is worth noting that you cannot use Scream to detect if device is in minimal-ui straight after the orientationchange event because window
dimensions do not reflect the new orientation until the rotation animation has ended. You have to attach a listener to the orientationchangeend event.
Scream and orientationchangeend have been developed as part of this project.
I have experienced this with my Tab Bar Controller not appearing in the Simulator along with a black screen. I did the following in order for my app to appear in the Simulator.
Is Initial View Controller
under the Attributes inspector tab.If you accidentally deleted that view controller, or otherwise made it not the default, then you’ll see the error “Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?” when your app launches, along with a plain black screen.
To fix the problem, open your Main.storyboard file and find whichever view controller you want to be shown when your app first runs. When it’s selected, go to the attributes inspector and check the box marked “Is Initial View Controller”. You should see a right-facing arrow appear to the left of that view controller, showing that it’s your storyboard’s entry point.
With java8 streaming API:
List values = map.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
if you want to open incognito window, put the command below:
start chrome /incognito
There is a difference between $(this)
and event.target
, and quite a significant one. While this
(or event.currentTarget
, see below) always refers to the DOM element the listener was attached to, event.target
is the actual DOM element that was clicked. Remember that due to event bubbling, if you have
<div class="outer">
<div class="inner"></div>
</div>
and attach click listener to the outer div
$('.outer').click( handler );
then the handler
will be invoked when you click inside the outer div as well as the inner one (unless you have other code that handles the event on the inner div and stops propagation).
In this example, when you click inside the inner div, then in the handler
:
this
refers to the .outer
DOM element (because that's the object to which the handler was attached)event.currentTarget
also refers to the .outer
element (because that's the current target element handling the event)event.target
refers to the .inner
element (this gives you the element where the event originated)The jQuery wrapper $(this)
only wraps the DOM element in a jQuery object so you can call jQuery functions on it. You can do the same with $(event.target)
.
Also note that if you rebind the context of this
(e.g. if you use Backbone it's done automatically), it will point to something else. You can always get the actual DOM element from event.currentTarget
.
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent
in an Activity
and then pass any extra data to fragments by instantiating them with arguments.
There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity
and Fragment
from the support library.
You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
public static class DetailsActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// (omitted some other stuff)
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
}
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance
in the examples given by Google. There actually is a newInstance
method in DetailsFragment
, so I'm unsure why it isn't used in the snippet above...
Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments()
. Since this returns a Bundle
, its usage is similar to that of the extras in an Activity
.
public static class DetailsFragment extends Fragment {
/**
* Create a new instance of DetailsFragment, initialized to
* show the text at 'index'.
*/
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
// (other stuff omitted)
}
You can get it at PuTTY: Extreme Makeover Using PuTTY Connection Manager.
To pop a message when the user is leaving the page to confirm leaving, you just do:
<script>
window.onbeforeunload = function(e) {
return 'Are you sure you want to leave this page? You will lose any unsaved data.';
};
</script>
To call a function:
<script>
window.onbeforeunload = function(e) {
callSomeFunction();
return null;
};
</script>
I strongly recommend you learn how to use layout managers to get the layout you want to see. null
layouts are fragile, and cause no end of trouble.
Try this source & check the comments.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class VolumeCalculator extends JFrame implements ActionListener {
private JTabbedPane jtabbedPane;
private JPanel options;
JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
myTitle;
JTextArea labelTubStatus;
public VolumeCalculator(){
setSize(400, 250);
setVisible(true);
setSize(400, 250);
setVisible(true);
setTitle("Volume Calculator");
setSize(300, 200);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
getContentPane().add(topPanel);
createOptions();
jtabbedPane = new JTabbedPane();
jtabbedPane.addTab("Options", options);
topPanel.add(jtabbedPane, BorderLayout.CENTER);
}
/* CREATE OPTIONS */
public void createOptions(){
options = new JPanel();
//options.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
options.add(labelOptions);
JTextField newTitle = new JTextField("Some Title");
//newTitle.setBounds(80, 40, 225, 20);
options.add(newTitle);
myTitle = new JTextField(20);
// myTitle WAS NEVER ADDED to the GUI!
options.add(myTitle);
//myTitle.setBounds(80, 40, 225, 20);
//myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
//newName.setBounds(60, 80, 150, 20);
newName.addActionListener(this);
options.add(newName);
JButton Exit = new JButton("Exit");
//Exit.setBounds(250, 80, 80, 20);
Exit.addActionListener(this);
options.add(Exit);
}
public void actionPerformed(ActionEvent event){
JButton button = (JButton) event.getSource();
String buttonLabel = button.getText();
if ("Exit".equalsIgnoreCase(buttonLabel)){
Exit_pressed();
return;
}
if ("Set New Name".equalsIgnoreCase(buttonLabel)){
New_Name();
return;
}
}
private void Exit_pressed(){
System.exit(0);
}
private void New_Name(){
System.out.println("'" + myTitle.getText() + "'");
this.setTitle(myTitle.getText());
}
private void Options(){
}
public static void main(String[] args){
JFrame frame = new VolumeCalculator();
frame.pack();
frame.setSize(380, 350);
frame.setVisible(true);
}
}
Such hack like "tabIndex=-1" not work for me with Chrome v53.
This is which works for chrome, and most browsers:
function removeTabIndex(element) {_x000D_
element.removeAttribute('tabindex');_x000D_
}
_x000D_
<input tabIndex="1" />_x000D_
<input tabIndex="2" id="notabindex" />_x000D_
<input tabIndex="3" />_x000D_
<button tabIndex="4" onclick="removeTabIndex(document.getElementById('notabindex'))">Remove tabindex</button>
_x000D_
This is how I managed to make it work:
jQuery( document ).ready(function($) {
$('.myHTMLvideo').click(function() {
this.paused ? this.play() : this.pause();
});
});
All my HTML5 tags have the class 'myHTMLvideo'
Or even shorter, with only standard modern Javascript:
var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));
The new MouseEvent
constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:
first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
If you get this error:
Cannot load 32-bit plugin, XMLTools.dll is not compatible with the current version of Notepad++
Here you can find a working version for Windows 10 x64: Xml Tools 2.4.9.2 Unicode
Note: It's the only version I've found working on Windows 10 Professional x64.
@Christian Ullenboom' explanation is correct.
I'm surmising that the OBD2nerForm
code you posted is a static initializer block and that it is all generated. Based on that and on the stack trace, it seems likely that generated code is tripping up because it has found some component of your form that doesn't have the type that it is expecting.
I'd do the following to try and diagnose this:
My suspicion is that the root cause is a combination of something a bit unusual (or incorrect) with your form design, and bugs in the NetBeans form generator that is not coping with your form. If you can figure it out, a workaround may reveal itself.
This is an old thread, but for reference it's important to note that disabling an input element's outline is not recommended as it hinders accessibility.
The outline property is there for a reason - providing users with a clear indication of keyboard focus. For further reading and additional sources about this subject see http://outlinenone.com/
Inspired by jfriend00, this worked for me
const seconds = new Date();
// wait 5 seconds for flag to become true
const waitTime = 5
const extraSeconds = seconds.setSeconds(seconds.getSeconds() + waitTime);
while (Date.now() < extraSeconds) {
// break when flag is false
if (flag === false) break;
}
_x000D_
You can use an array of pointer to (homogeneous) member data to enable a dual, named-member (i.e. x.data) and array-subscript (i.e. x[idx]) interface.
#include <cassert>
#include <cstddef>
struct vector3 {
float x;
float y;
float z;
float& operator[](std::size_t idx) {
static float vector3::*component[3] = {
&vector3::x, &vector3::y, &vector3::z
};
return this->*component[idx];
}
};
int main()
{
vector3 v = { 0.0f, 1.0f, 2.0f };
assert(&v[0] == &v.x);
assert(&v[1] == &v.y);
assert(&v[2] == &v.z);
for (std::size_t i = 0; i < 3; ++i) {
v[i] += 1.0f;
}
assert(v.x == 1.0f);
assert(v.y == 2.0f);
assert(v.z == 3.0f);
return 0;
}
# The following would be a very simple solution.
print("")
string = input("Enter your string :")
noofspacesinstring = 0
for counter in string:
if counter == " ":
noofspacesinstring += 1
if noofspacesinstring == 0:
message = "Your string is a single word"
else:
message = "Your string is not a single word"
print("")
print(message)
print("")
Many years later...
The accepted answer of using the OUTPUT clause is good. I had to dig up the actual syntax, so here it is:
DECLARE @UpdatedIDs table (ID int)
UPDATE
Table1
SET
AlertDate = getutcdate()
OUTPUT
inserted.Id
INTO
@UpdatedIDs
WHERE
AlertDate IS NULL;
ADDED SEP 14, 2015:
"Can I use a scalar variable instead of a table variable?" one may ask... Sorry, but no you can't. You'll have to SELECT @SomeID = ID from @UpdatedIDs
if you need a single ID.
import os
def file_path(relative_path):
dir = os.path.dirname(os.path.abspath(__file__))
split_path = relative_path.split("/")
new_path = os.path.join(dir, *split_path)
return new_path
with open(file_path("2091/data.txt"), "w") as f:
f.write("Powerful you have become.")
I got the "hunks failed" message when I wasn't applying the patch in the top directory of the associated git project. I was applying the patch (where I created it) in a subdirectory.
It seems patches can be created from subdirectories within a git project, but not applied.
Can I use (http://caniuse.com/#feat=datauri) shows support across the major browsers with few issues on IE.
When pthread_exit() is called, the calling threads stack is no longer addressable as "active" memory for any other thread. The .data, .text and .bss parts of "static" memory allocations are still available to all other threads. Thus, if you need to pass some memory value into pthread_exit() for some other pthread_join() caller to see, it needs to be "available" for the thread calling pthread_join() to use. It should be allocated with malloc()/new, allocated on the pthread_join threads stack, 1) a stack value which the pthread_join caller passed to pthread_create or otherwise made available to the thread calling pthread_exit(), or 2) a static .bss allocated value.
It's vital to understand how memory is managed between a threads stack, and values store in .data/.bss memory sections which are used to store process wide values.
Use ModHeader Chrome extension.
Or you can try more complex value like Accept-Language: en-US,en;q=0.9,ru;q=0.8,th;q=0.7
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
Just came across this problem myself, and the only solution I could find that worked in all my test browsers (IE6, IE7, Firefox) was the following:
The code:
<div style="width: 100%">
<div style="padding-right: 6px;">
<input type="text" style="width: 100%; padding: 2px; margin: 0;
border : solid 1px #999" />
</div>
</div>
Here, the total horizontal overflow for the input element is 6px - 2x(padding + border) - so we set a padding-right for the inner DIV of 6px.
According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO
option or a certificate directory can be specified with the CURLOPT_CAPATH
option.
Also look at CURLOPT_SSL_VERIFYHOST:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
I posted that in jQuery forums (I hope it can help):
Diving into the jQM code i've found this solution. I hope it can help other people:
To refresh a dynamically modified page:
function refreshPage(page){
// Page refresh
page.trigger('pagecreate');
page.listview('refresh');
}
It works even if you create new headers, navbars or footers. I've tested it with jQM 1.0.1.
You may use ViewModel object in your activity.
ViewModel objects are automatically retained during configuration changes so that data they hold is immediately available to the next activity or fragment instance. Read more:
https://developer.android.com/topic/libraries/architecture/viewmodel
Not exactly zipping, but you can compact files in Windows with the compact command:
compact /c /s:<directory or file>
And to uncompress:
compact /u /s:<directory or file>
NOTE: These commands only mark/unmark files or directories as compressed in the file system. They do not produces any kind of archive (like zip, 7zip, rar, etc.)
Every InvoiceItem
must have an Invoice
attached to it because of the not-null="true"
in the many-to-one mapping.
So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a setItems
method. I do NOT see an addInvoiceItem
method. When you set items, you need to loop through the set and call item.setInvoice(this)
on all of the items. If you implement an addItem
method, you need to do the same thing. Or you need to otherwise set the Invoice of every InvoiceItem
in the collection.
hey dominic your answer was nice but if your have a site like http://localhost/project/index.php the 'project' link gets repeated since it's part of $base and also appears in the $path array. So I tweaked and removed the first item in the $path array.
//Trying to remove the first item in the array path so it doesn't repeat
array_shift($path);
I dont know if that is the most elegant way, but it now works for me.
I add that code before this one on line 13 or something
// Find out the index for the last value in our path array
$last = end(array_keys($path));
To see all commands that are being executed by the script, add the -x
flag to your shabang line, and execute the command normally:
#! /bin/bash -x
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include="$include" server::team_l_start="${teamAComm}" server::team_r_start="${teamBComm}" CSVSaver::save='true' CSVSaver::filename='out.csv'
Then if you sometimes want to ignore the debug output, redirect stderr
somewhere.
Before increasing the max_connections variable, you have to check how many non-interactive connection you have by running show processlist command.
If you have many sleep connection, you have to decrease the value of the "wait_timeout" variable to close non-interactive connection after waiting some times.
SHOW SESSION VARIABLES LIKE 'wait_timeout';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout | 28800 |
+---------------+-------+
the value is in second, it means that non-interactive connection still up to 8 hours.
SET session wait_timeout=600; Query OK, 0 rows affected (0.00 sec)
After 10 minutes if the sleep connection still sleeping the mysql or MariaDB drop that connection.
Generally we want to add images, txt, doc and etc files inside our Java project and specific folder such as /images. I found in search that in JAVA, we can get path from Root to folder which we specify as,
String myStorageFolder= "/images"; // this is folder name in where I want to store files.
String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);
Here, request is object of HttpServletRequest. It will get the whole path from Root to /images folder. You will get output like,
C:\Users\STARK\Workspaces\MyEclipse.metadata.me_tcat7\webapps\JavaProject\images
Take a look at the open source WordPress application. They have a very re-usable window they have created for displaying an "activity in progress" type display over top of whatever view your application is currently displaying.
http://iphone.trac.wordpress.org/browser/trunk
The files you want are:
Then to show it use something like:
[[WPActivityIndicator sharedActivityIndicator] show];
And hide with:
[[WPActivityIndicator sharedActivityIndicator] hide];
I think as a rule of thumb, if your if-expression can be re-written as
const bool local_predicate = *if-expression*;
if (local_predicate) ...
such that it causes NO WARNINGS, then THAT should be the preferred style for the if-expression. (I know I get warnings when I assign an old C BOOL
(#define BOOL int
) to a C++ bool
, let alone pointers.)
In your case, if you want to Foo.talk()
:
function Foo() {};
// But use Foo.talk would be inefficient
Foo.talk = function () {
alert('hello~\n');
};
Foo.talk(); // 'hello~\n'
But it's an inefficient way to implement, using prototype
is better.
Another way, My way is defined as static class:
var Foo = new function() {
this.talk = function () {
alert('hello~\n');
};
};
Foo.talk(); // 'hello~\n'
Above static class doesn't need to use prototype
because it will be only constructed once as static usage.
https://github.com/yidas/js-design-patterns/tree/master/class
Following works out for me.
#!/usr/bin/env python
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
found_event = next(
filter(
lambda x: x['main_color'] == 'red',
a
),
#return this dict when not found
dict(
name='red',
value='{}'
)
)
if found_event:
print(found_event)
$python /tmp/x
{'main_color': 'red', 'second_color': 'blue'}
For most of my select options, I start off with an option that simply says 'Please Select' or something similar and that option is always disabled. Then whenever you want to clear your select/option's you can do just do something like this.
Example
<select id="mySelectOption">
<option value="" selected disabled>Please select</option>
</select>
Answer
$('#mySelectOption').val('Please Select');
Late to the party, but the tsbox package is designed to perform conversions like this. To convert your data into a ts
-object, you can do:
dta <- data.frame(
Dates = c("3/14/2013", "3/15/2013", "3/18/2013", "3/19/2013"),
Bajaj_close = c(1854.8, 1850.3, 1812.1, 1835.9),
Hero_close = c(1669.1, 1684.45, 1690.5, 1645.6)
)
dta
#> Dates Bajaj_close Hero_close
#> 1 3/14/2013 1854.8 1669.10
#> 2 3/15/2013 1850.3 1684.45
#> 3 3/18/2013 1812.1 1690.50
#> 4 3/19/2013 1835.9 1645.60
library(tsbox)
ts_ts(ts_long(dta))
#> Time Series:
#> Start = 2013.1971293045
#> End = 2013.21081883954
#> Frequency = 365.2425
#> Bajaj_close Hero_close
#> 2013.197 1854.8 1669.10
#> 2013.200 1850.3 1684.45
#> 2013.203 NA NA
#> 2013.205 NA NA
#> 2013.208 1812.1 1690.50
#> 2013.211 1835.9 1645.60
It automatically parses the dates, detects the frequency and makes the missing values at the weekends explicit. With ts_<class>
, you can convert the data to any other time series class.
sudo apt-get update
OpenGL: sudo apt-get install libglu1-mesa-dev freeglut3-dev mesa-common-dev
Locate your Visual Studio folder for where it puts libraries and also header files, download and copy lib files to lib folder and header files to header. Then copy dll files to system32. Then your code will 100% run.
Also Windows: For all of those includes you just need to download glut32.lib
, glut.h
, glut32.dll
.
this one is working
$.get('1.txt', function(data) {
//var fileDom = $(data);
var lines = data.split("\n");
$.each(lines, function(n, elem) {
$('#myContainer').append('<div>' + elem + '</div>');
});
});
I completely agree with @Peter Rasmussen.
Design patterns provide general solution to commonly occurring design problem.
I would like you to follow below approach.
Useful links:
sourcemaking : Explains intent, structure and checklist beautifully in multiple languages including C++ and Java
wikipedia : Explains structure, UML diagram and working examples in multiple languages including C# and Java .
Check list and Rules of thumb in each sourcemakding design-pattern provides alram bell you are looking for.
use trap
to pause and check command line (in color using tput
) before running it
trap 'tput setaf 1;tput bold;echo $BASH_COMMAND;read;tput init' DEBUG
press any key to continue
use with
set -x
to debug command line
1 Close Android Studio (AS)
2 Delete the folder in C:\Users.gradle\wrapper\dists\gradle-2.1-all
3 Run AS as admin
4 Sync your project files
You can declare a new type:
declare type MyHandler = (myArgument: string) => void;
var handler: MyHandler;
The declare
keyword is not necessary. It should be used in the .d.ts files or in similar cases.
Red Hat, Fedora:
sudo dnf -y install gcc-c++ redhat-rpm-config ruby-devel gcc mysql-devel rubygems
From the information you have specified, your best chance of recovery is through a database backup. I don't think you're going to be able to rollback any of those changes you pushed through since you were apparently not using transactions at the time.
You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load
method of your Test.aspx.cs
file.
Write code in this manner ...
<canvas id="canvas" width="640" height="480"></canvas>
<script>
var Grid = function(width, height) {
...
this.draw = function() {
var canvas = document.getElementById("canvas");
if(canvas.getContext) {
var context = canvas.getContext("2d");
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
if(isLive(i, j)) {
context.fillStyle = "lightblue";
}
else {
context.fillStyle = "yellowgreen";
}
context.fillRect(i*15, j*15, 14, 14);
}
}
}
}
}
First write canvas tag and then write script tag. And write script tag in body.
Use find. Seriously, it is the best way because then you can really see what files it's operating on:
find . -name "*.sql" -exec grep -H "slow" {} \;
Note, the -H is mac-specific, it shows the filename in the results.
If you're inside a front contoller servlet which is mapped on a prefix pattern such as /foo/*
, then you can just use HttpServletRequest#getPathInfo()
.
String pathInfo = request.getPathInfo();
// ...
Assuming that the servlet in your example is mapped on /secure/*
, then this will return /users
which would be the information of sole interest inside a typical front controller servlet.
If the servlet is however mapped on a suffix pattern such as *.foo
(your URL examples however does not indicate that this is the case), or when you're actually inside a filter (when the to-be-invoked servlet is not necessarily determined yet, so getPathInfo()
could return null
), then your best bet is to substring the request URI yourself based on the context path's length using the usual String
method:
HttpServletRequest request = (HttpServletRequest) req;
String path = request.getRequestURI().substring(request.getContextPath().length());
// ...
The $
symbol simply invokes the jQuery library's selector functionality. So $("#Text")
returns the jQuery object for the Text
div
which can then be modified.
My best guess at why you had problems with the ----- covering your first result is that you actually read the input line from a file. That line probably had a \r on the end so you ended up with something like this:
-----------test2-------test3
What happened is the machine actually printed this:
test-------test2-------test3\r-------
That means, because of the carriage return at the end of test3, that the dashes after test3 were printed over the top of the first word (and a few of the existing dashes between test and test2 but you wouldn't notice that because they were already dashes).
int i = 0;
bool b = Convert.ToBoolean(i);
If you look at the line which is causing the error, you'll see this:
from numpy._distributor_init import NUMPY_MKL # requires numpy+mkl
This line comment states the dependency as numpy+mkl
(numpy
with Intel Math Kernel Library). This means that you've installed the numpy
by pip
, but the scipy
was installed by precompiled archive, which expects numpy+mkl
.
This problem can be easy solved by installation for numpy+mkl
from whl file from here.
var="a b c"
for i in $var
do
p=`echo -e "$p"'\n'$i`
done
echo "$p"
The solution was simply to protect the inserted newline with a "" during current iteration when variable substitution happens.
With HTML5 you can do
<input type="number">
You can also use a regex pattern to limit the input text.
<input type="text" pattern="^[0-9]*$" />
Parsing is about READING data in one format, so that you can use it to your needs.
I think you need to teach them to think like this. So, this is the simplest way I can think of to explain parsing for someone new to this concept.
Generally, we try to parse data one line at a time because generally it is easier for humans to think this way, dividing and conquering, and also easier to code.
We call field to every minimum undivisible data. Name is field, Age is another field, and Surname is another field. For example.
In a line, we can have various fields. In order to distinguish them, we can delimit fields by separators or by the maximum length assign to each field.
For example: By separating fields by comma
Paul,20,Jones
Or by space (Name can have 20 letters max, age up to 3 digits, Jones up to 20 letters)
Paul 020Jones
Any of the before set of fields is called a record.
To separate between a delimited field record we need to delimit record. A dot will be enough (though you know you can apply CR/LF).
A list could be:
Michael,39,Jordan.Shaquille,40,O'neal.Lebron,24,James.
or with CR/LF
Michael,39,Jordan
Shaquille,40,O'neal
Lebron,24,James
You can say them to list 10 nba (or nlf) players they like. Then, they should type them according to a format. Then make a program to parse it and display each record. One group, can make list in a comma-separated format and a program to parse a list in a fixed size format, and viceversa.
You can use the expandable list view explained in API demos to show groups
To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.
You can extract that part of the URL using a simple regular expression:
var url = location.href;
var className = url.match(/\w+\/(\w+)_/)[1];
$('body').addClass(className);
I'm assuming what you want to do is run a command without an interface (possibly automatically?). On windows there are a number of options for what you are looking for:
Best: write your program as a windows service. These will start when no one logs into the server. They let you select the user account (which can be different than your own) and they will restart if they fail. These run all the time so you can automate tasks at specific times or on a regular schedule from within them. For more information on how to write a windows service you can read a tutorial online such as (http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx).
Better: Start the command and hide the window. Assuming the command is a DOS command you can use a VB or C# script for this. See here for more information. An example is:
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("C:\yourbatch.bat"), 0, True
You are still going to have to start the command manually or write a task to start the command. This is one of the biggest down falls of this strategy.
Hope that helps some!
How about doing this by creating a function in javascript as shown below:
function msToTime(duration) {_x000D_
var milliseconds = parseInt((duration % 1000) / 100),_x000D_
seconds = Math.floor((duration / 1000) % 60),_x000D_
minutes = Math.floor((duration / (1000 * 60)) % 60),_x000D_
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);_x000D_
_x000D_
hours = (hours < 10) ? "0" + hours : hours;_x000D_
minutes = (minutes < 10) ? "0" + minutes : minutes;_x000D_
seconds = (seconds < 10) ? "0" + seconds : seconds;_x000D_
_x000D_
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;_x000D_
}_x000D_
console.log(msToTime(300000))
_x000D_
You said it worked fine when you were using SQL Express edition. By default express editions create a named instance & run in NT Authority\Network Service.
SQL Server STD by default install a default instance & run in NT Authority\SYSTEM.
Do you have both the full SQL edition & Express edition installed on the same machine?
It could be that somewhere the connection string still refers to the Named instance 'SQLEXPRESS' rather than the default instance created by the full version.
Also where is the connection string defined? In IIS or your code? Make sure that if defined in many places, all point to same SQL instance & database.
Also try looking at the detailed error present in the SQL Server error logs. The error logged in event log are not complete for secuirty reasons. This will also help you to know if the connection was made to the correct SQL Server.
Also make sure that the machine on which SQL is installed is accessible & IIS is trying to access the same machine. In my company sometimes due to wrong name resolution, the query fails since most of our computers have SQL installed & the query lands in the wrong SQL Server.
Make sure that the database exists in the SQL Server. The name displayed under databases in SQL Management Studio should match that in the connection string.
I'd use something like:
dim customer = (from c in xmldoc...<Customer>
where c.<ID>.Value=22
select c).SingleOrDefault
Edit:
missed the c# tag, sorry......the example is in VB.NET
Using ES6 solution
For those still reading this answer, if you are using ES6 the find
method was added in arrays. So assuming the same collection, the solution'd be:
const foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
foo.results.find(item => item.id === 2)
I'd totally go for this solution now, as is less tied to angular or any other framework. Pure Javascript.
Angular solution (old solution)
I aimed to solve this problem by doing the following:
$filter('filter')(foo.results, {id: 1})[0];
A use case example:
app.controller('FooCtrl', ['$filter', function($filter) {
var foo = { "results": [
{
"id": 12,
"name": "Test"
},
{
"id": 2,
"name": "Beispiel"
},
{
"id": 3,
"name": "Sample"
}
] };
// We filter the array by id, the result is an array
// so we select the element 0
single_object = $filter('filter')(foo.results, function (d) {return d.id === 2;})[0];
// If you want to see the result, just check the log
console.log(single_object);
}]);
Plunker: http://plnkr.co/edit/5E7FYqNNqDuqFBlyDqRh?p=preview
If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:
=SUMIF(B:B,"No",A:A)
or
=SUMIFS(A:A,B:B,"No")
Here is an example that will display the amounts paid and outstanding for a small set of sample data.
A B C D
Amount Reimbursed? Total Paid: =SUMIF(B:B,"Yes",A:A)
$100 Yes Total Outstanding: =SUMIF(B:B,"No",A:A)
$200 No
$300 No
$400 Yes
$500 No
Following Step to to enable disable ARC
Select Xcode project Go to targets Select the Build phases section Inside the build phases section select the compile sources. Select the file which you do not want to disable ARC and add -fno-objc-arc
There is a bug in Chrome (not in Safari at the time we checked) that gives unexpected results in Javascript's various width and height measurements when opening tabs in the background (bug details here) - we logged the bug in June and it's remained unresolved since.
It's possible you've encountered the bug in what you're attempting to do.
It depends on what type of fading you are looking for.
But with shadow and rounded corners you can get a nice result. Rounded corners because the bigger the shadow, the weirder it will look in the edges unless you balance it out with rounded corners.
also.. http://css3pie.com/
TLDR: they are equivalent Error(x) === new Error(x)
.
// this:
const x = Error('I was created using a function call!');
????// has the same functionality as this:
const y = new Error('I was constructed via the "new" keyword!');
source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error
throw and throw Error will are functionally equivalent. But when you catch them and serialize them to console.log they are not serialized exactly the same way:
throw 'Parameter is not a number!';
throw new Error('Parameter is not a number!');
throw Error('Parameter is not a number!');
Console.log(e) of the above will produce 2 different results:
Parameter is not a number!
Error: Parameter is not a number!
Error: Parameter is not a number!
You're looking for the zip builtin function. From the docs:
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
Adding import android.support.v7.widget.Toolbar to the import list resolve this issue.
Then add the toolbar widget layout file:
<android.support.v7.widget.Toolbar
android:id="@+id/list_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
/>
In onCreate method of java code
//call to
Tootbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar);
Source: https://developer.android.com/training/appbar/up-action
For those who look for a safe client-side solution that also works on server-side, there is genversion. It is a command-line tool that reads the version from the nearest package.json and generates an importable CommonJS module file that exports the version. Disclaimer: I'm a maintainer.
$ genversion lib/version.js
I acknowledge the client-side safety was not OP's primary intention, but as discussed in answers by Mark Wallace and aug, it is highly relevant and also the reason I found this Q&A.
PARTITION BY
segregate sets, this enables you to be able to work(ROW_NUMBER(),COUNT(),SUM(),etc) on related set independently.
In your query, the related set comprised of rows with similar cdt.country_code, cdt.account, cdt.currency. When you partition on those columns and you apply ROW_NUMBER on them. Those other columns on those combination/set will receive sequential number from ROW_NUMBER
But that query is funny, if your partition by some unique data and you put a row_number on it, it will just produce same number. It's like you do an ORDER BY on a partition that is guaranteed to be unique. Example, think of GUID as unique combination of cdt.country_code, cdt.account, cdt.currency
newid()
produces GUID, so what shall you expect by this expression?
select
hi,ho,
row_number() over(partition by newid() order by hi,ho)
from tbl;
...Right, all the partitioned(none was partitioned, every row is partitioned in their own row) rows' row_numbers are all set to 1
Basically, you should partition on non-unique columns. ORDER BY on OVER needed the PARTITION BY to have a non-unique combination, otherwise all row_numbers will become 1
An example, this is your data:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','Y'),
('A','Z'),
('B','W'),
('B','W'),
('C','L'),
('C','L');
Then this is analogous to your query:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho)
from tbl;
What will be the output of that?
HI HO COLUMN_2
A X 1
A Y 1
A Z 1
B W 1
B W 2
C L 1
C L 2
You see thee combination of HI HO? The first three rows has unique combination, hence they are set to 1, the B rows has same W, hence different ROW_NUMBERS, likewise with HI C rows.
Now, why is the ORDER BY
needed there? If the previous developer merely want to put a row_number on similar data (e.g. HI B, all data are B-W, B-W), he can just do this:
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
But alas, Oracle(and Sql Server too) doesn't allow partition with no ORDER BY
; whereas in Postgresql, ORDER BY
on PARTITION is optional: http://www.sqlfiddle.com/#!1/27821/1
select
hi,ho,
row_number() over(partition by hi,ho)
from tbl;
Your ORDER BY
on your partition look a bit redundant, not because of the previous developer's fault, some database just don't allow PARTITION
with no ORDER BY
, he might not able find a good candidate column to sort on. If both PARTITION BY columns and ORDER BY columns are the same just remove the ORDER BY, but since some database don't allow it, you can just do this:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account, cdt.currency
ORDER BY newid())
seq_no
FROM CUSTOMER_DETAILS cdt
You cannot find a good column to use for sorting similar data? You might as well sort on random, the partitioned data have the same values anyway. You can use GUID for example(you use newid()
for SQL Server). So that has the same output made by previous developer, it's unfortunate that some database doesn't allow PARTITION
with no ORDER BY
Though really, it eludes me and I cannot find a good reason to put a number on the same combinations (B-W, B-W in example above). It's giving the impression of database having redundant data. Somehow reminded me of this: How to get one unique record from the same list of records from table? No Unique constraint in the table
It really looks arcane seeing a PARTITION BY with same combination of columns with ORDER BY, can not easily infer the code's intent.
Live test: http://www.sqlfiddle.com/#!3/27821/6
But as dbaseman have noticed also, it's useless to partition and order on same columns.
You have a set of data like this:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','X'),
('A','X'),
('A','X'),
('B','Y'),
('B','Y'),
('C','Z'),
('C','Z');
Then you PARTITION BY hi,ho; and then you ORDER BY hi,ho. There's no sense numbering similar data :-) http://www.sqlfiddle.com/#!3/29ab8/3
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
Output:
HI HO ROW_QUERY_A
A X 1
A X 2
A X 3
B Y 1
B Y 2
C Z 1
C Z 2
See? Why need to put row numbers on same combination? What you will analyze on triple A,X, on double B,Y, on double C,Z? :-)
You just need to use PARTITION on non-unique column, then you sort on non-unique column(s)'s unique-ing column. Example will make it more clear:
create table tbl(hi varchar, ho varchar);
insert into tbl values
('A','D'),
('A','E'),
('A','F'),
('B','F'),
('B','E'),
('C','E'),
('C','D');
select
hi,ho,
row_number() over(partition by hi order by ho) as nr
from tbl;
PARTITION BY hi
operates on non unique column, then on each partitioned column, you order on its unique column(ho), ORDER BY ho
Output:
HI HO NR
A D 1
A E 2
A F 3
B E 1
B F 2
C D 1
C E 2
That data set makes more sense
Live test: http://www.sqlfiddle.com/#!3/d0b44/1
And this is similar to your query with same columns on both PARTITION BY and ORDER BY:
select
hi,ho,
row_number() over(partition by hi,ho order by hi,ho) as nr
from tbl;
And this is the ouput:
HI HO NR
A D 1
A E 1
A F 1
B E 1
B F 1
C D 1
C E 1
See? no sense?
Live test: http://www.sqlfiddle.com/#!3/d0b44/3
Finally this might be the right query:
SELECT cdt.*,
ROW_NUMBER ()
OVER (PARTITION BY cdt.country_code, cdt.account -- removed: cdt.currency
ORDER BY
-- removed: cdt.country_code, cdt.account,
cdt.currency) -- keep
seq_no
FROM CUSTOMER_DETAILS cdt
Consider building an Add-on that has an actual button and not using the outdated method of linking an image to a script function.
In the script editor, under the Help menu >> Welcome Screen >> link to Google Sheets Add-on - will give you sample code to use.
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Wireshark + OSX + iOS:
Great overview so far, but if you want specifics for Wireshark + OSX + iOS:
rvictl -s x
where x
is the UDID of your iOS device. You can find the UDID of your iOS device via iTunes (make sure you are using the UDID and not the serial number).Capture->Options
, a dialog box appears, click on the line rvi0
then press the Start
button.Now you will see all network traffic on the iOS device. It can be pretty overwhelming. A couple of pointers:
ip.addr==204.144.14.134
views traffic with a source or destination address of 204.144.14.134http
views only http trafficHere's a sample window depicting TCP traffic for for pdf download from 204.144.14.134:
When you create table than you can give like follows.
CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;
CREATE TABLE products(
prd_id int not null auto_increment primary key,
prd_name varchar(355) not null,
prd_price decimal,
cat_id int not null,
FOREIGN KEY fk_cat(cat_id)
REFERENCES categories(cat_id)
ON UPDATE CASCADE
ON DELETE RESTRICT
)ENGINE=InnoDB;
and when after the table create like this
ALTER table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name(columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action;
Following on example for it.
CREATE TABLE vendors(
vdr_id int not null auto_increment primary key,
vdr_name varchar(255)
)ENGINE=InnoDB;
ALTER TABLE products
ADD COLUMN vdr_id int not null AFTER cat_id;
To add a foreign key to the products table, you use the following statement:
ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
For drop the key
ALTER TABLE table_name
DROP FOREIGN KEY constraint_name;
Hope this help to learn FOREIGN keys works
12
is a compile-time constant which can not be changed unlike the data referenced by int&
. What you can do is
const int& z = 12;
You should use the key() function.
key($array)
should return the current key.
If you need the position of the current key:
array_search($key, array_keys($array));
Consider the following for-comprehension
val A = for (i <- Int.MinValue to Int.MaxValue; if i > 3) yield i
It may be helpful to read it out loud as follows
"For each integer i
, if it is greater than 3
, then yield (produce) i
and add it to the list A
."
In terms of mathematical set-builder notation, the above for-comprehension is analogous to
which may be read as
"For each integer , if it is greater than , then it is a member of the set ."
or alternatively as
" is the set of all integers , such that each is greater than ."
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
As far as when AWT may be more useful than Swing -
I will add this as a reason to locally host these files.
Recently a node in Southern California on TWC has not been able to resolve the ajax.googleapis.com domain (for users with IPv4) only so we are not getting the external files. This has been intermittant up until yesterday (now it is persistant.) Because it was intermittant, I was having tons of problems troubleshooting SaaS user issues. Spent countless hours trying to track why some users were having no issues with the software, and others were tanking. In my usual debugging process I'm not in the habit of asking a user if they have IPv6 turned off.
I stumbled on the issue because I myself was using this particular "route" to the file and also am using only IPV4. I discovered the issue with developers tools telling me jquery wasn't loading, then started doing traceroutes etc... to find the real issue.
After this, I will most likely never go back to externally hosted files because: google doesn't have to go down for this to become a problem, and... any one of these nodes can be compromised with DNS hijacking and deliver malicious js instead of the actual file. Always thought I was safe in that a google domain would never go down, now I know any node in between a user and the host can be a fail point.
Instead of using a sheet name, in case you don't know or can't open the excel file to check in ubuntu (in my case, Python 3.6.7, ubuntu 18.04), I use the parameter index_col (index_col=0 for the first sheet)
import pandas as pd
file_name = 'some_data_file.xlsx'
df = pd.read_excel(file_name, index_col=0)
print(df.head()) # print the first 5 rows
Now you can use new html5 input validation attribute pattern=".+\.(xlsx|xls|csv)"
.
Here's my take on the problem. I create AbsoluteLayout
overlay which contains Info Window (a regular view with every bit of interactivity and drawing capabilities). Then I start Handler
which synchronizes the info window's position with position of point on the map every 16 ms. Sounds crazy, but actually works.
Demo video: https://www.youtube.com/watch?v=bT9RpH4p9mU (take into account that performance is decreased because of emulator and video recording running simultaneously).
Code of the demo: https://github.com/deville/info-window-demo
An article providing details (in Russian): http://habrahabr.ru/post/213415/
Suppose your existing reporting query is
Select EmployeeId,EmployeeName
from Employee
Where EmployeeId>101 order by EmployeeName
and you have to save this data into temparory table then you query goes to
Select EmployeeId,EmployeeName
into #MyTempTable
from Employee
Where EmployeeId>101 order by EmployeeName
Another way to do this by writing less code.
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile('index.html');
});
I tried the steps mentioned in the earlier posts but without any success. However, what worked for me was uninstalling R completely and then deleting the R folder which files in the documents folder, so basically everything do with R except the scripts and work spaces I had saved. I then reinstalled R and ran
remove.packages(c("ggplot2", "data.table"))
install.packages('Rcpp', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)
install.packages('data.table', dependencies = TRUE)
This rather crude method somehow worked for me.
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
Based on the accepted answer I created an Extension method as follows:
public static Guid ToGuid(this string aString)
{
Guid newGuid;
if (string.IsNullOrWhiteSpace(aString))
{
return MagicNumbers.defaultGuid;
}
if (Guid.TryParse(aString, out newGuid))
{
return newGuid;
}
return MagicNumbers.defaultGuid;
}
Where "MagicNumbers.defaultGuid" is just "an empty" all zero Guid "00000000-0000-0000-0000-000000000000".
In my case returning that value as the result of an invalid ToGuid conversion was not a problem.
I had the same issue when I changed the home directory of one use. In my case it was because of selinux
. I used the below to fix the issue:
selinuxenabled 0
setenforce 0
Just use the Cells function and loop thru columns. Cells(Row,Column)
BufferedReader
has significantly larger buffer memory than Scanner. Use BufferedReader
if you want to get long strings from a stream, and use Scanner
if you want to parse specific type of token from a stream.
Scanner
can use tokenize using custom delimiter and parse the stream into primitive types of data, while BufferedReader
can only read and store String.
BufferedReader
is synchronous while Scanner
is not. Use BufferedReader
if you're working with multiple threads.
Scanner
hides IOException while BufferedReader
throws it immediately.
I found that switching to use full html instead of filtered html (below the editor in the Text Format dropdown box) is what fixed this problem for me. Otherwise the style would disappear.
If someone is using Gradle, then put this in build.gradle
java {
sourceCompatibility = JavaVersion.VERSION_1_7
targetCompatibility = JavaVersion.VERSION_1_7
}
We are telling the compiler to enable the byte code to be compatable with version java 7(java version in which i want to run the class) in the above case.
structure is collection of different data type where different type of data can reside in it and every one get its own block of memory
we usually used union when we sure that only one of the variable will be used at once and you want fully utilization of present memory because it get only one block of memory which is equal to the biggest type.
struct emp
{
char x;//1 byte
float y; //4 byte
} e;
total memory it get =>5 byte
union emp
{
char x;//1 byte
float y; //4 byte
} e;
total memory it get =4 byte
I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.
shell request failed on channel 0
mean you don't have shell or remote commands access, fix your user permission on server to have shell access or if you just want tunneling use -N
and -T
options
There are some working solutions here already, but here's another one:
>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True
Your response should be something like this to be qualified as Json Array.
{
"songs":[
{"2562862600": {"id":"2562862600", "pos":1}},
{"2562862620": {"id":"2562862620", "pos":1}},
{"2562862604": {"id":"2562862604", "pos":1}},
{"2573433638": {"id":"2573433638", "pos":1}}
]
}
You can parse your response as follows
String resp = ...//String output from your source
JSONObject ob = new JSONObject(resp);
JSONArray arr = ob.getJSONArray("songs");
for(int i=0; i<arr.length(); i++){
JSONObject o = arr.getJSONObject(i);
System.out.println(o);
}
# s1 == source string
# char == find this character
# repl == replace with this character
def findreplace(s1, char, repl):
s1 = s1.replace(char, repl)
return s1
# find each 'i' in the string and replace with a 'u'
print findreplace('it is icy', 'i', 'u')
# output
''' ut us ucy '''
On windows, I have observed that this issue shows up if you do not have administrative rights (i.e., you are not a local administrator) on the machine.
As someone else suggested, the solution seems to be to install locally by not using the -g
hint.
If your host is using suPHP, you can try creating a php.ini
file in the same folder as the script and adding:
allow_url_fopen = On
(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script
<?php
echo `id`;
?>
To give the same information, assuming shell_exec
is not a disabled function)
You could do something like:
find . -type d > dirs.txt
to create the list of directories, then
xargs mkdir -p < dirs.txt
to create the directories on the destination.
Just before executing the query: alter session set NLS_DATE_FORMAT = "DD.MM.YYYY HH24:MI:SS"; or whichever format you are giving the information to the date function. This should fix the ORA error
Looping through all the files in the folder is relatively easy:
files = dir('*.csv');
for file = files'
csv = load(file.name);
% Do some stuff
end
Try (bonus)
let hex2rgb= c=> `rgb(${c.substr(1).match(/../g).map(x=>+`0x${x}`)})`;
let rgb2hex= c=>'#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``
let hex2rgb= c=> `rgb(${c.substr(1).match(/../g).map(x=>+`0x${x}`)})`;
let rgb2hex= c=> '#'+c.match(/\d+/g).map(x=>(+x).toString(16).padStart(2,0)).join``;
// TEST
console.log('#0080C0 -->', hex2rgb('#0080C0'));
console.log('rgb(0, 128, 192) -->', rgb2hex('rgb(0, 128, 192)'));
_x000D_
I'm going out on a limb here , since your question was not very detailed, that a) your receipt printer is a thermal printer that needs raw data, b) that "from javascript" you are talking about printing from the web browser and c) that you do not have access to send raw data from browser
Here is a Java Applet that solves all that for you , if I'm correct about those assumptions then you need either Java, Flash, or Silverlight http://code.google.com/p/jzebra/
The only thing missing hidden from Rob W's excellent answer is how to communicate between the injected page script and the content script.
On the receiving side (either your content script or the injected page script) add an event listener:
document.addEventListener('yourCustomEvent', function (e) {
var data = e.detail;
console.log('received', data);
});
On the initiator side (content script or injected page script) send the event:
var data = {
allowedTypes: 'those supported by structured cloning, see the list below',
inShort: 'no DOM elements or classes/functions',
};
document.dispatchEvent(new CustomEvent('yourCustomEvent', { detail: data }));
Notes:
In Firefox, to send an object (i.e. not a primitive value) from the content script to the page context you have to explicitly clone it into the target using cloneInto
(a built-in function), otherwise it'll fail with a security violation error.
document.dispatchEvent(new CustomEvent('yourCustomEvent', {
detail: cloneInto(data, document.defaultView),
}));
This will keep the \n character, but you can also just wrap the quote in parentheses. Especially useful in RMarkdown.
t <- ("
this is a long
string
")
No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me
class line_details {
var $commission_one=array();
foreach($_SESSION['commission'] as $key=>$data){
$row= explode('-', $key);
$this->commission_one[$row['0']]= $row['1'];
}
}
Direct download:
Go to the project repository from the dashboard of bitbucket. Select downloads from the left menu. Choose Download repository.
According to this answer, you just don't include minsdkversion in the manifest.xml, and the build system will use the values from the build.gradle file and put the information into the final apk.
Because the build system needs this information anyway, this makes sense. You should not need to define this values two times.
You just have to sync the project after changing the build.gradle
file, but Android Studio 0.5.2 display a yellow status bar on top of the build.gradle editor window to help you
Also note there at least two build.gradle
files: one master and one for the app/module. The one to change is in the app/module, it already includes a property minSdkVersion
in a newly generated project.
The child views in your list row should be considered selected whenever the parent row is selected, so you should be able to just set a normal state drawable/color-list on the views you want to change, no messy Java code necessary. See this SO post.
Specifically, you'd set the textColor
of your textViews to an XML resource like this one:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@color/black" /> <!-- focused -->
<item android:state_focused="true" android:state_pressed="true" android:drawable="@color/black" /> <!-- focused and pressed-->
<item android:state_pressed="true" android:drawable="@color/green" /> <!-- pressed -->
<item android:drawable="@color/black" /> <!-- default -->
</selector>
var x = $(this).attr("name");
$("#" + x).hide();
I'm not familiar with either of these books, but the second is closer to current reality. The first may be discussing a specific processor.
Processors have been made with quite a variety of word sizes, not always a multiple of 8.
The 8086 and 8087 processors used 16 bit words, and it's likely this is the machine the first author was writing about.
More recent processors commonly use 32 or 64 bit words.
In the 50's and 60's there were machines with words sizes that seem quite strange to us now, such as 4, 9 and 36. Since about the 70's word size has commonly been a power of 2 and a multiple of 8.
You could kill all connections before dropping the database using the pg_terminate_backend(int)
function.
You can get all running backends using the system view pg_stat_activity
I'm not entirely sure, but the following would probably kill all sessions:
select pg_terminate_backend(procpid)
from pg_stat_activity
where datname = 'doomed_database'
Of course you may not be connected yourself to that database
There are at least three places where you may find shared_ptr
:
If your C++ implementation supports C++11 (or at least the C++11 shared_ptr
), then std::shared_ptr
will be defined in <memory>
.
If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr
will likely be in <memory>
(Microsoft Visual C++) or <tr1/memory>
(g++'s libstdc++). Boost also provides a TR1 implementation that you can use.
Otherwise, you can obtain the Boost libraries and use boost::shared_ptr
, which can be found in <boost/shared_ptr.hpp>
.
Although I've used Eclipse for years, this "answer" is only conjecture (which I'm going to try tonight). If it gets down-voted out of existence, then obviously I'm wrong.
Oracle relies on CMake to generate a Visual Studio "Solution" for their MySQL Connector C source code. Within the Solution are "Projects" that can be compiled individually or collectively (by the Solution). Each Project has its own makefile, compiling its portion of the Solution with settings that are different than the other Projects.
Similarly, I'm hoping an Eclipse Workspace can hold my related makefile Projects (Eclipse), with a master Project whose dependencies compile the various unique-makefile Projects as pre-requesites to building its "Solution". (My folder structure would be as @Rafael describes).
So I'm hoping a good way to use Workspaces is to emulate Visual Studio's ability to combine dissimilar Projects into a Solution.
To sum it up:
You can use the dialog from Visual Basic by adding a reference to Microsoft.VisualBasic:
Then you can use the previously mentioned code:
string input = Microsoft.VisualBasic.Interaction.InputBox("Prompt", "Title", "Default", 0, 0);
That said, I suggest that you consider the need of an input box in the first place. Dialogs are not always the best way to do things and sometimes they do more harm than good - but that depends on the particular situation.
PYTHONPATH
is an environment variable those content is added to the sys.path
where Python looks for modules. You can set it to whatever you like.
However, do not mess with PYTHONPATH
. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…
I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.
HTML
<a href="#top">Top</a>
<a href="#middle">Middle</a>
<a href="#bottom">Bottom</a>
<div id="top"><a href="top"></a>Top</div>
<div id="middle"><a href="middle"></a>Middle</div>
<div id="bottom"><a href="bottom"></a>Bottom</div>
CSS
#top,#middle,#bottom{
height: 600px;
width: 300px;
background: green;
}
Example http://jsfiddle.net/x4wDk/
You can make this connection in interface builder.
In your storyboard, click the assistant editor at the top of the screen (two circles in the middle).
Ctrl + Click on the textfield in interface builder.
Drag from EditingChanged to inside your view controller class in the assistant view.
Name your function ("textDidChange" for example) and click connect.
Here's how I solved it. This works if you also use this for editing.
@Html.TextBoxFor(m => m.Age, new { Value = Model.Age.ToString() ?? "0" })
This is how I would go about it.
$posts = $this->post->orderBy('id', 'DESC')->get();
Some times it just happens due to installation of Wamp or changing of password options of root user. One can use privilages-->root (user) and then set password option to NO to run the things without any password OR set the password and use it in the application.
function SingletonClass()
{
// demo variable
var names = [];
// instance of the singleton
this.singletonInstance = null;
// Get the instance of the SingletonClass
// If there is no instance in this.singletonInstance, instanciate one
var getInstance = function() {
if (!this.singletonInstance) {
// create a instance
this.singletonInstance = createInstance();
}
// return the instance of the singletonClass
return this.singletonInstance;
}
// function for the creation of the SingletonClass class
var createInstance = function() {
// public methodes
return {
add : function(name) {
names.push(name);
},
names : function() {
return names;
}
}
}
// wen constructed the getInstance is automaticly called and return the SingletonClass instance
return getInstance();
}
var obj1 = new SingletonClass();
obj1.add("Jim");
console.log(obj1.names());
// prints: ["Jim"]
var obj2 = new SingletonClass();
obj2.add("Ralph");
console.log(obj1.names());
// Ralph is added to the singleton instance and there for also acceseble by obj1
// prints: ["Jim", "Ralph"]
console.log(obj2.names());
// prints: ["Jim", "Ralph"]
obj1.add("Bart");
console.log(obj2.names());
// prints: ["Jim", "Ralph", "Bart"]
Assuming there are no prepending/succeeding whitespace characters, there are still a few ways to assert string equality. Some of those are:
strings.ToLower(..)
then ==
strings.EqualFold(.., ..)
cases#Lower
paired with ==
cases#Fold
paired with ==
Here are some basic benchmark results (in these tests, strings.EqualFold(.., ..)
seems like the most performant choice):
goos: darwin
goarch: amd64
BenchmarkStringOps/both_strings_equal::equality_op-4 10000 182944 ns/op
BenchmarkStringOps/both_strings_equal::strings_equal_fold-4 10000 114371 ns/op
BenchmarkStringOps/both_strings_equal::fold_caser-4 10000 2599013 ns/op
BenchmarkStringOps/both_strings_equal::lower_caser-4 10000 3592486 ns/op
BenchmarkStringOps/one_string_in_caps::equality_op-4 10000 417780 ns/op
BenchmarkStringOps/one_string_in_caps::strings_equal_fold-4 10000 153509 ns/op
BenchmarkStringOps/one_string_in_caps::fold_caser-4 10000 3039782 ns/op
BenchmarkStringOps/one_string_in_caps::lower_caser-4 10000 3861189 ns/op
BenchmarkStringOps/weird_casing_situation::equality_op-4 10000 619104 ns/op
BenchmarkStringOps/weird_casing_situation::strings_equal_fold-4 10000 148489 ns/op
BenchmarkStringOps/weird_casing_situation::fold_caser-4 10000 3603943 ns/op
BenchmarkStringOps/weird_casing_situation::lower_caser-4 10000 3637832 ns/op
Since there are quite a few options, so here's the code to generate benchmarks.
package main
import (
"fmt"
"strings"
"testing"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func BenchmarkStringOps(b *testing.B) {
foldCaser := cases.Fold()
lowerCaser := cases.Lower(language.English)
tests := []struct{
description string
first, second string
}{
{
description: "both strings equal",
first: "aaaa",
second: "aaaa",
},
{
description: "one string in caps",
first: "aaaa",
second: "AAAA",
},
{
description: "weird casing situation",
first: "aAaA",
second: "AaAa",
},
}
for _, tt := range tests {
b.Run(fmt.Sprintf("%s::equality op", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringEqualsOperation(tt.first, tt.second, b)
}
})
b.Run(fmt.Sprintf("%s::strings equal fold", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsEqualFold(tt.first, tt.second, b)
}
})
b.Run(fmt.Sprintf("%s::fold caser", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsFoldCaser(tt.first, tt.second, foldCaser, b)
}
})
b.Run(fmt.Sprintf("%s::lower caser", tt.description), func(b *testing.B) {
for i := 0; i < b.N; i++ {
benchmarkStringsLowerCaser(tt.first, tt.second, lowerCaser, b)
}
})
}
}
func benchmarkStringEqualsOperation(first, second string, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = strings.ToLower(first) == strings.ToLower(second)
}
}
func benchmarkStringsEqualFold(first, second string, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = strings.EqualFold(first, second)
}
}
func benchmarkStringsFoldCaser(first, second string, caser cases.Caser, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = caser.String(first) == caser.String(second)
}
}
func benchmarkStringsLowerCaser(first, second string, caser cases.Caser, b *testing.B) {
for n := 0; n < b.N; n++ {
_ = caser.String(first) == caser.String(second)
}
}
The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".
The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.
There is also another straight and more clear way
git commit -m "Title" -m "Description ..........";
I would always use a Unix timestamp when working with MySQL and PHP. The main reason for this being the default date method in PHP uses a timestamp as the parameter, so there would be no parsing needed.
To get the current Unix timestamp in PHP, just do time();
and in MySQL do SELECT UNIX_TIMESTAMP();
.
It involves eyeballing it (well I suppose you could get out a calculator and calculate) but just insert said control on the form and then remove any anchoring (anchor = None).
We can always pass html content to innerHTML
property to render html dynamic content but that dynamic html content can be infected or malicious also. So before passing dynamic content to innerHTML
we should always make sure the content is sanitized (using DOMSanitizer
) so that we can escaped all malicious content.
Try below pipe:
import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";
@Pipe({name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {
}
transform(value: string) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
Usage:
<div [innerHTML]="content | safeHtml"></div>
From the documentation page
To set the page type pass the value in constructor
jsPDF(orientation, unit, format)
Creates new jsPDF document objectinstance Parameters:
orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'
To set font size
setFontSize(size)
Sets font size for upcoming text elements.
Parameters:
{Number} size Font size in points.
Create a .htaccess file in directory and add this code to .htaccess file
AddHandler x-httpd-php .html .htm
or
AddType application/x-httpd-php .html .htm
It will force Apache server to parse HTML or HTM files as PHP Script
html {
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
This make the scrollbar always visible and only active when needed.
Update: If the above does not work the just using this may.
html {
overflow-y:scroll;
}
_x000D_
table tbody_x000D_
{_x000D_
border:1px solid red;_x000D_
}_x000D_
table td_x000D_
{_x000D_
background:yellow;_x000D_
_x000D_
border-bottom:1px solid green;_x000D_
_x000D_
_x000D_
}_x000D_
.tr0{_x000D_
line-height:0;_x000D_
}_x000D_
.tr0 td{_x000D_
background:red;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr><td>test</td></tr>_x000D_
<tr><td>test</td></tr> _x000D_
<tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
This page is a interesting read on the topic: http://home.tiac.net/~cri_d/cri/2001/badsort.html
My personal favorite is Tom Duff's sillysort:
/*
* The time complexity of this thing is O(n^(a log n))
* for some constant a. This is a multiply and surrender
* algorithm: one that continues multiplying subproblems
* as long as possible until their solution can no longer
* be postponed.
*/
void sillysort(int a[], int i, int j){
int t, m;
for(;i!=j;--j){
m=(i+j)/2;
sillysort(a, i, m);
sillysort(a, m+1, j);
if(a[m]>a[j]){ t=a[m]; a[m]=a[j]; a[j]=t; }
}
}
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Using dt.weekday_name
is deprecated since pandas 0.23.0
, instead, use dt.day_name()
:
df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['my_dates'].dt.day_name()
0 Thursday
1 Friday
2 Saturday
Name: my_dates, dtype: object
((EditText) findViewById(R.id.User)).setText("");
((EditText) findViewById(R.id.Password)).setText("");
Here is an article with full details on how to do this.
Private Sub btnScale_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnScale.Click
' Get the scale factor.
Dim scale_factor As Single = Single.Parse(txtScale.Text)
' Get the source bitmap.
Dim bm_source As New Bitmap(picSource.Image)
' Make a bitmap for the result.
Dim bm_dest As New Bitmap( _
CInt(bm_source.Width * scale_factor), _
CInt(bm_source.Height * scale_factor))
' Make a Graphics object for the result Bitmap.
Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)
' Copy the source image into the destination bitmap.
gr_dest.DrawImage(bm_source, 0, 0, _
bm_dest.Width + 1, _
bm_dest.Height + 1)
' Display the result.
picDest.Image = bm_dest
End Sub
[Edit]
One more on the similar lines.
As Wagner Francisco said, (in JADE)
input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`
And in your controller :
$scope.someScopeVariable = 'somevalue'
Below can be 2 reasons for this issue:
Backup taken on SQL 2012 and Restore Headeronly was done in SQL 2008 R2
Backup media is corrupted.
If we run below command, we can find actual error always:
restore headeronly
from disk = 'C:\Users\Public\Database.bak'
Give complete location of your database file in the quot
Hope it helps
Yes. The sorted
built-in accepts a key
argument:
sorted(li,key=lambda x: x[1])
Out[31]: [['Jason', 1], ['John', 2], ['Jim', 9]]
note that sorted
returns a new list. If you want to sort in-place, use the .sort
method of your list (which also, conveniently, accepts a key
argument).
or alternatively,
from operator import itemgetter
sorted(li,key=itemgetter(1))
Out[33]: [['Jason', 1], ['John', 2], ['Jim', 9]]
We can get KEY
from VALUE
. Below is a sample code_
public class Main {
public static void main(String[] args) {
Map map = new HashMap();
map.put("key_1","one");
map.put("key_2","two");
map.put("key_3","three");
map.put("key_4","four");
System.out.println(getKeyFromValue(map,"four"));
}
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
}
I hope this will help everyone.
Here is a good start maybe
Have a look in the examples for a number of different formating options Double.ToString(string)
I'm not entirely sure that I've understood the question because this is a fairly straightforward answer, but here goes... :)
Have you tried setting the overflow property of the container to visible or auto?
#some_div {
height:100%;
background:black;
overflow: visible;
}
Adding that should push the black container to whatever size your dynamic container requires. I prefer visible to auto because auto seems to come with scroll bars...
You need a dict
:
my_dict = {'cheese': 'cake'}
Example code (from the docs):
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
You can read more about dictionaries here.
String is a class in Java different from other programming languages. So as for every class the object declaration and initialization is
String st1 = new String();
or
String st2 = new String("Hello");
String st3 = new String("Hello");
Here, st1
, st2
and st3
are different objects.
That is:
st1 == st2 // false
st1 == st3 // false
st2 == st3 // false
Because st1
, st2
, st3
are referencing 3 different objects, and ==
checks for the equality in memory location, hence the result.
But:
st1.equals(st2) // false
st2.equals(st3) // true
Here .equals()
method checks for the content, and the content of st1 = ""
, st2 = "hello"
and st3 = "hello"
. Hence the result.
And in the case of the String declaration
String st = "hello";
Here, intern()
method of String
class is called, and checks if "hello"
is in intern pool, and if not, it is added to intern pool, and if "hello" exist in intern pool, then st
will point to the memory of the existing "hello"
.
So in case of:
String st3 = "hello";
String st4 = "hello";
Here:
st3 == st4 // true
Because st3
and st4
pointing to same memory address.
Also:
st3.equals(st4); // true as usual
You are missing table NewScores
, so it can't be found. Just join this table.
If you really want to avoid joining it directly you can replace NewScores.NetScore
with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}
If they are in the same controller class, it would be:
foreach ( $characters as $character) {
$num += $this->getFactorial($index) * $index;
$index ++;
}
Otherwise you need to create a new instance of the class, and call the method, ie:
$controller = new MyController();
foreach ( $characters as $character) {
$num += $controller->getFactorial($index) * $index;
$index ++;
}
In case you want to run a PowerShell script with Windows Task Scheduler, please follow the steps below:
Create a task
Set Program/Script
to Powershell.exe
Set Arguments
to -File "C:\xxx.ps1"
It's from another answer, How do I execute a PowerShell script automatically using Windows task scheduler?.
With java lambdas (available since java 8) you can simply convert javax.swing.filechooser.FileFilter
to java.io.FileFilter
in one line.
javax.swing.filechooser.FileFilter swingFilter = new FileNameExtensionFilter("jpeg files", "jpeg");
java.io.FileFilter ioFilter = file -> swingFilter.accept(file);
new File("myDirectory").listFiles(ioFilter);
ARIA (Accessible Rich Internet Applications) defines a way to make Web content and Web applications more accessible to people with disabilities.
The hidden
attribute is new in HTML5 and tells browsers not to display the element. The aria-hidden
property tells screen-readers if they should ignore the element. Have a look at the w3 docs for more details:
https://www.w3.org/WAI/PF/aria/states_and_properties#aria-hidden
Using these standards can make it easier for disabled people to use the web.
By getting the getLastKnownLocation
you do not actually initiate a fix yourself.
Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.
According to the docs getLastKnownLocation:
Returns a Location indicating the data from the last known location fix obtained from the given provider. This can be done without starting the provider.
Here is a quick snippet:
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;
public class UtilLocation {
public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Location utilLocation = null;
List<String> providers = manager.getProviders(enabledProvidersOnly);
for(String provider : providers){
utilLocation = manager.getLastKnownLocation(provider);
if(utilLocation != null) return utilLocation;
}
return null;
}
}
You also have to add new permission to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
@media only screen and (max-width: 1026px) {
#fadeshow1 {
display: none;
}
}
Any time the screen is less than 1026 pixels wide, anything inside the { }
will apply.
Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS
var str = 'Hello World',
i = 3,
result = str.substr(0, i-1)+str.substring(i);
alert(result);
Value of i
should not be less then 1
.
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
button {
background:transparent;
border:none;
outline:none;
display:block;
height:200px;
width:200px;
cursor:pointer;
}
Give the height and width with respect to the image in the background.This removes the borders and color of a button.You might also need to position it absolute so you can correctly place it where you need.I cant help you further without posting you code
To make it truly invisible you have to set outline:none; otherwise there would be a blue outline in some browsers and you have to set display:block if you need to click it and set dimensions to it
For a valid JSON string at least a "{}" is required. See more at the http://json.org/
In most cases, it really doesn't matter that much. Just pick a good size such as 4K or 16K and stick with it. If you're positive that this is the bottleneck in your application, then you should start profiling to find the optimal buffer size. If you pick a size that's too small, you'll waste time doing extra I/O operations and extra function calls. If you pick a size that's too big, you'll start seeing a lot of cache misses which will really slow you down. Don't use a buffer bigger than your L2 cache size.
By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );
jsonConfig.setRootClass( Integer.TYPE );
int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );
There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)
app.Use(async (httpContext, next) =>
{
CallContext.LogicalSetData("CurrentContextKey", httpContext);
try
{
await next();
}
finally
{
CallContext.FreeNamedDataSlot("CurrentContextKey");
}
});
And when you need it you can get it with :
HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;
I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.
Whatsapp store all messages in an encrypted database (pyCrypt) which is very easy to decipher using Python.
You can fetch this database easily on Android, iPhone, Blackberry and dump it into html file. Here are complete instructions: Read, Extract WhatsApp Messages backup on Android, iPhone, Blackberry
Disclaimer: I researched and wrote this extensive guide.
Python 2, using lambda
>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
I have a setup like this:
I then have a helper function that simply returns the full path to this depending on my setup, something similar to:
application/helpers/utility_helper.php:
function asset_url(){
return base_url().'assets/';
}
I will usually keep common routines similar to this in the same file and autoload it with codeigniter's autoload configuration.
Note: autoload URL helper for
base_url()
access.
application/config/autoload.php:
$autoload['helper'] = array('url','utility');
You will then have access to asset_url()
throughout your code.
Save as fix_whitespace.py
:
#!/usr/bin/env python
"""
Fix trailing whitespace and line endings (to Unix) in a file.
Usage: python fix_whitespace.py foo.py
"""
import os
import sys
def main():
""" Parse arguments, then fix whitespace in the given file """
if len(sys.argv) == 2:
fname = sys.argv[1]
if not os.path.exists(fname):
print("Python file not found: %s" % sys.argv[1])
sys.exit(1)
else:
print("Invalid arguments. Usage: python fix_whitespace.py foo.py")
sys.exit(1)
fix_whitespace(fname)
def fix_whitespace(fname):
""" Fix whitespace in a file """
with open(fname, "rb") as fo:
original_contents = fo.read()
# "rU" Universal line endings to Unix
with open(fname, "rU") as fo:
contents = fo.read()
lines = contents.split("\n")
fixed = 0
for k, line in enumerate(lines):
new_line = line.rstrip()
if len(line) != len(new_line):
lines[k] = new_line
fixed += 1
with open(fname, "wb") as fo:
fo.write("\n".join(lines))
if fixed or contents != original_contents:
print("************* %s" % os.path.basename(fname))
if fixed:
slines = "lines" if fixed > 1 else "line"
print("Fixed trailing whitespace on %d %s" \
% (fixed, slines))
if contents != original_contents:
print("Fixed line endings to Unix (\\n)")
if __name__ == "__main__":
main()
.values.reshape(-1,1)
will be accepted without alerts/warnings
.reshape(-1,1)
will be accepted, but with deprecation war
I used this, and it worked perfectly.
error: function(xhr, status, error){
alertify.error(JSON.parse(xhr.responseText).error);
}
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
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)
.
That code looks like the route you want to take with a few changes.
You'll want to change the append method to look like this. I've changed it to accept the number 0, and to make it return this
so you can chain your appends.
StringBuilder.prototype.append = function (value) {
if (value || value === 0) {
this.strings.push(value);
}
return this;
}
SourceForge uses MongoDB. See this presentation or read here.
Invoke the sqlite3
utility on the database file, and use its special dot commands:
.tables
will list tables.schema [tablename]
will show the CREATE statement(s) for a table or tablesThere are many other useful builtin dot commands -- see the documentation at http://www.sqlite.org/sqlite.html, section Special commands to sqlite3.
Example:
sqlite> entropy:~/Library/Mail>sqlite3 Envelope\ Index
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
addresses ews_folders subjects
alarms feeds threads
associations mailboxes todo_notes
attachments messages todos
calendars properties todos_deleted_log
events recipients todos_server_snapshot
sqlite> .schema alarms
CREATE TABLE alarms (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, alarm_id,
todo INTEGER, flags INTEGER, offset_days INTEGER,
reminder_date INTEGER, time INTEGER, argument,
unrecognized_data BLOB);
CREATE INDEX alarm_id_index ON alarms(alarm_id);
CREATE INDEX alarm_todo_index ON alarms(todo);
Note also that SQLite saves the schema and all information about tables in the database itself, in a magic table named sqlite_master, and it's also possible to execute normal SQL queries against that table. For example, the documentation link above shows how to derive the behavior of the .schema
and .tables
commands, using normal SQL commands (see section: Querying the database schema).
This is a simple way to show a spinner that does not require a third-party library, intercepters, or jQuery.
In the controller, set and reset a flag.
function starting() {
//ADD SPINNER
vm.starting = true;
$http.get(url)
.then(function onSuccess(response) {
vm.data = response.data;
}).catch(function onReject(errorResponse) {
console.log(errorResponse.status);
}).finally(function() {
//REMOVE SPINNER
vm.starting = false;
});
};
In the HTML, use the flag:
<div ng-show="vm.starting">
<img ng-src="spinnerURL" />
</div>
<div ng-hide="vm.starting">
<p>{{vm.data}}</p>
</div>
The vm.starting
flag is set true
when the XHR starts and cleared when the XHR completes.
If using Guava library, there are methods Ints.checkedCast(long)
and Ints.saturatedCast(long)
for converting long
to int
.
Found the solution here
Lets say you have span1 as <span id='span1'>my text</span>
text change events can be captured with:
$(document).ready(function(){
$("#span1").on('DOMSubtreeModified',function(){
// text change handler
});
});
The reason to prefer Promises over callback functions is to have multiple callbacks and to avoid the problems like Callback Hell.
Callback hell (for more details, refer http://callbackhell.com/): Asynchronous javascript, or javascript that uses callbacks, is hard to get right intuitively. A lot of code ends up looking like this:
asyncCall(function(err, data1){
if(err) return callback(err);
anotherAsyncCall(function(err2, data2){
if(err2) return calllback(err2);
oneMoreAsyncCall(function(err3, data3){
if(err3) return callback(err3);
// are we done yet?
});
});
});
With Promises above code can be rewritten as below:
asyncCall()
.then(function(data1){
// do something...
return anotherAsyncCall();
})
.then(function(data2){
// do something...
return oneMoreAsyncCall();
})
.then(function(data3){
// the third and final async response
})
.fail(function(err) {
// handle any error resulting from any of the above calls
})
.done();
Yes, that is the difference, the Add method throws an exception if the key already exists.
The reason to use the Add method is exactly this. If the dictionary is not supposed to contain the key already, you usually want the exception so that you are made aware of the problem.
create .bowerrc file in you home directory and adding this to the file worked for me
{
"directory": "bower_components",
"proxy": "http://youProxy:yourPort",
"https-proxy":"http://yourProxy:yourPort"
}
You post JSON like this
$.ajax(url, {
data : JSON.stringify(myJSObject),
contentType : 'application/json',
type : 'POST',
...
if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want
Maybe you want unpack elements of array, I don't know if I got it, but below a example:
def my_func(*args):
for a in args:
print a
my_func(*[1,2,3,4])
my_list = ['a','b','c']
my_func(*my_list)
The difference is the name of the mangled identifier (_ZN12_GLOBAL__N_11bE
vs _ZL1b
, which doesn't really matter, but both of them are assembled to local symbols in the symbol table (absence of .global
asm directive).
#include<iostream>
namespace {
int a = 3;
}
static int b = 4;
int c = 5;
int main (){
std::cout << a << b << c;
}
.data
.align 4
.type _ZN12_GLOBAL__N_11aE, @object
.size _ZN12_GLOBAL__N_11aE, 4
_ZN12_GLOBAL__N_11aE:
.long 3
.align 4
.type _ZL1b, @object
.size _ZL1b, 4
_ZL1b:
.long 4
.globl c
.align 4
.type c, @object
.size c, 4
c:
.long 5
.text
As for a nested anonymous namespace:
namespace {
namespace {
int a = 3;
}
}
.data
.align 4
.type _ZN12_GLOBAL__N_112_GLOBAL__N_11aE, @object
.size _ZN12_GLOBAL__N_112_GLOBAL__N_11aE, 4
_ZN12_GLOBAL__N_112_GLOBAL__N_11aE:
.long 3
All 1st level anonymous namespaces in the translation unit are combined with each other, All 2nd level nested anonymous namespaces in the translation unit are combined with each other
You can also have a nested namespace or nested inline namespace in an anonymous namespace
namespace {
namespace A {
int a = 3;
}
}
.data
.align 4
.type _ZN12_GLOBAL__N_11A1aE, @object
.size _ZN12_GLOBAL__N_11A1aE, 4
_ZN12_GLOBAL__N_11A1aE:
.long 3
which for the record demangles as:
.data
.align 4
.type (anonymous namespace)::A::a, @object
.size (anonymous namespace)::A::a, 4
(anonymous namespace)::A::a:
.long 3
//inline has the same output
You can also have anonymous inline namespaces, but as far as I can tell, inline
on an anonymous namespace has 0 effect
inline namespace {
inline namespace {
int a = 3;
}
}
_ZL1b
: _Z
means this is a mangled identifier. L
means it is a local symbol through static
. 1
is the length of the identifier b
and then the identifier b
_ZN12_GLOBAL__N_11aE
_Z
means this is a mangled identifier. N
means this is a namespace 12
is the length of the anonymous namespace name _GLOBAL__N_1
, then the anonymous namespace name _GLOBAL__N_1
, then 1
is the length of the identifier a
, a
is the identifier a
and E
closes the identifier that resides in a namespace.
_ZN12_GLOBAL__N_11A1aE
is the same as above except there's another namespace level in it 1A
You can simply use $_GET
especially if you know the othervar
's name.
If you want to be on the safe side, use if (isset ($_GET ['varname']))
to test for existence.
numpy has arrays that allow you to use other lists/arrays as indices:
import numpy
S=numpy.array(s)
S[a]=m
My guess is your PHP installation wasn't compiled with MySQL support.
Check your configure command (php -i | grep mysql
). You should see something like '--with-mysql=shared,/usr'
.
You can check for complete instructions at http://php.net/manual/en/mysql.installation.php. Although, I would rather go with the solution proposed by @wanovak.
Still, I think you need MySQL support in order to use PDO.
<script type="text/JavaScript">
var script = document.createElement('SCRIPT');
script.src = 'YOURJAVASCRIPTURL';
document.getElementsByTagName('HEAD')[0].appendChild(script);
</script>
I was having the same problem until I read Jon Skeet's answer about the debugger displaying a single backslash with a double backslash even though the string may have a single backslash. I was not aware of that. So I changed my code from
text2 = text1.Replace(@"\\", @"/");
to
text2 = text1.Replace(@"\", @"/");
and that solved the problem. Note: I'm interfacing and R.Net which uses single forward slashes in path strings.
You can create an unsigned char:
unsigned char c = 0xc5;
Printing it will give C5
and not ffffffc5
.
Only the chars bigger than 127 are printed with the ffffff
because they are negative (char is signed).
Or you can cast the char
while printing:
char c = 0xc5;
printf("%x", (unsigned char)c);
I've been given to understand that Python is an interpreted language...
This popular meme is incorrect, or, rather, constructed upon a misunderstanding of (natural) language levels: a similar mistake would be to say "the Bible is a hardcover book". Let me explain that simile...
"The Bible" is "a book" in the sense of being a class of (actual, physical objects identified as) books; the books identified as "copies of the Bible" are supposed to have something fundamental in common (the contents, although even those can be in different languages, with different acceptable translations, levels of footnotes and other annotations) -- however, those books are perfectly well allowed to differ in a myriad of aspects that are not considered fundamental -- kind of binding, color of binding, font(s) used in the printing, illustrations if any, wide writable margins or not, numbers and kinds of builtin bookmarks, and so on, and so forth.
It's quite possible that a typical printing of the Bible would indeed be in hardcover binding -- after all, it's a book that's typically meant to be read over and over, bookmarked at several places, thumbed through looking for given chapter-and-verse pointers, etc, etc, and a good hardcover binding can make a given copy last longer under such use. However, these are mundane (practical) issues that cannot be used to determine whether a given actual book object is a copy of the Bible or not: paperback printings are perfectly possible!
Similarly, Python is "a language" in the sense of defining a class of language implementations which must all be similar in some fundamental respects (syntax, most semantics except those parts of those where they're explicitly allowed to differ) but are fully allowed to differ in just about every "implementation" detail -- including how they deal with the source files they're given, whether they compile the sources to some lower level forms (and, if so, which form -- and whether they save such compiled forms, to disk or elsewhere), how they execute said forms, and so forth.
The classical implementation, CPython, is often called just "Python" for short -- but it's just one of several production-quality implementations, side by side with Microsoft's IronPython (which compiles to CLR codes, i.e., ".NET"), Jython (which compiles to JVM codes), PyPy (which is written in Python itself and can compile to a huge variety of "back-end" forms including "just-in-time" generated machine language). They're all Python (=="implementations of the Python language") just like many superficially different book objects can all be Bibles (=="copies of The Bible").
If you're interested in CPython specifically: it compiles the source files into a Python-specific lower-level form (known as "bytecode"), does so automatically when needed (when there is no bytecode file corresponding to a source file, or the bytecode file is older than the source or compiled by a different Python version), usually saves the bytecode files to disk (to avoid recompiling them in the future). OTOH IronPython will typically compile to CLR codes (saving them to disk or not, depending) and Jython to JVM codes (saving them to disk or not -- it will use the .class
extension if it does save them).
These lower level forms are then executed by appropriate "virtual machines" also known as "interpreters" -- the CPython VM, the .Net runtime, the Java VM (aka JVM), as appropriate.
So, in this sense (what do typical implementations do), Python is an "interpreted language" if and only if C# and Java are: all of them have a typical implementation strategy of producing bytecode first, then executing it via a VM/interpreter.
More likely the focus is on how "heavy", slow, and high-ceremony the compilation process is. CPython is designed to compile as fast as possible, as lightweight as possible, with as little ceremony as feasible -- the compiler does very little error checking and optimization, so it can run fast and in small amounts of memory, which in turns lets it be run automatically and transparently whenever needed, without the user even needing to be aware that there is a compilation going on, most of the time. Java and C# typically accept more work during compilation (and therefore don't perform automatic compilation) in order to check errors more thoroughly and perform more optimizations. It's a continuum of gray scales, not a black or white situation, and it would be utterly arbitrary to put a threshold at some given level and say that only above that level you call it "compilation"!-)
The docs give a fair indicator of what's required., however requests
allow us to skip a few steps:
You only need to install the security
package extras (thanks @admdrew for pointing it out)
$ pip install requests[security]
or, install them directly:
$ pip install pyopenssl ndg-httpsclient pyasn1
Requests will then automatically inject pyopenssl
into urllib3
If you're on ubuntu, you may run into trouble installing pyopenssl
, you'll need these dependencies:
$ apt-get install libffi-dev libssl-dev
Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method
Following the documentation of fopen
:
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.
So if you pFile2=fopen("myfile2.txt", "a");
the stream is positioned at the end to append automatically. just do:
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(fgets(buffer, sizeof(buffer), pFile)) {
fprintf(pFile2, "%s", buffer);
}
}
fclose(pFile);
fclose(pFile2);
SilverSkin and Anders are both correct. You can use parentheses to execute multiple commands. However, you have to make sure that the commands themselves (and their parameters) do not contain parentheses. cmd
greedily searches for the first closing parenthesis, instead of handling nested sets of parentheses gracefully. This may cause the rest of the command line to fail to parse, or it may cause some of the parentheses to get passed to the commands (e.g. DEL myfile.txt)
).
A workaround for this is to split the body of the loop into a separate function. Note that you probably need to jump around the function body to avoid "falling through" into it.
FOR /r %%X IN (*.txt) DO CALL :loopbody %%X
REM Don't "fall through" to :loopbody.
GOTO :EOF
:loopbody
ECHO %1
DEL %1
GOTO :EOF
Here's an example of strtok
usage, keep in mind that strtok
is destructive of its input string (and therefore can't ever be used on a string constant
char *p = strtok(str, " ");
while(p != NULL) {
printf("%s\n", p);
p = strtok(NULL, " ");
}
Basically the thing to note is that passing a NULL
as the first parameter to strtok
tells it to get the next token from the string it was previously tokenizing.
This is probably what you're looking for in terms of thread safety & "prettyness" when trying to consume everything in the queue:
for (YourObject obj = queue.poll(); obj != null; obj = queue.poll()) {
}
This will guarantee that you quit when the queue is empty, and that you continue to pop objects off of it as long as it's not empty.
You need to move the unique_ptr
:
vec.push_back(std::move(ptr2x));
unique_ptr
guarantees that a single unique_ptr
container has ownership of the held pointer. This means that you can't make copies of a unique_ptr
(because then two unique_ptr
s would have ownership), so you can only move it.
Note, however, that your current use of unique_ptr
is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:
std::unique_ptr<int> ptr(new int(1));
In C++14 we have an even better way to do so:
make_unique<int>(5);
There's always the hardware route. Purchase two USB to serial converters, and connect them via a NULL modem.
Pro tips: 1) Windows may assign new COM ports to the adapters after every device sleep or reboot. 2) The market leaders in chips for USB to serial are Prolific and FTDI. Both companies are battling knockoffs, and may be blocked in future official Windows drivers. The Linux drivers however work fine with the clones.
TL; DR
This might also be caused by applying OR
to string columns / literals.
Full version
I got the same error message for a simple INSERT
statement involving a view:
insert into t1 select * from v1
although all the source and target columns were of type VARCHAR
. After some debugging, I found the root cause; the view contained this fragment:
string_col1 OR '_' OR string_col2 OR '_' OR string_col3
which presumably was the result of an automatic conversion of the following snippet from Oracle:
string_col1 || '_' || string_col2 || '_' || string_col3
(||
is string concatenation in Oracle). The solution was to use
concat(string_col1, '_', string_col2, '_', string_col3)
instead.
To deselect all rows and cells in a DataGridView
, you can use the ClearSelection
method:
myDataGridView.ClearSelection()
If you don't want even the first row/cell to appear selected, you can set the CurrentCell
property to Nothing
/null
, which will temporarily hide the focus rectangle until the control receives focus again:
myDataGridView.CurrentCell = Nothing
To determine when the user has clicked on a blank part of the DataGridView
, you're going to have to handle its MouseUp
event. In that event, you can HitTest
the click location and watch for this to indicate HitTestInfo.Nowhere
. For example:
Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
''# See if the left mouse button was clicked
If e.Button = MouseButtons.Left Then
''# Check the HitTest information for this click location
If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
myDataGridView.ClearSelection()
myDataGridView.CurrentCell = Nothing
End If
End If
End Sub
Of course, you could also subclass the existing DataGridView
control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp
method similar to the way shown above. I also like to provide a public DeselectAll
method for convenience that both calls the ClearSelection
method and sets the CurrentCell
property to Nothing
.
(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)
I have decided to compile this answer because all others seem to be incomplete.
config.active_record.default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database. The default is :utc. http://guides.rubyonrails.org/configuring.html
If you want to change Rails timezone, but continue to have Active Record save in the database in UTC, use
# application.rb
config.time_zone = 'Eastern Time (US & Canada)'
If you want to change Rails timezone AND have Active Record store times in this timezone, use
# application.rb
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local
Warning: you really should think twice, even thrice, before saving times in the database in a non-UTC format.
Note
Do not forget to restart your Rails server after modifyingapplication.rb
.
Remember that config.active_record.default_timezone
can take only two values
config.time_zone
)Here's how you can find all available timezones
rake time:zones:all
Use toString
when you need to display the name to the user.
Use name
when you need the name for your program itself, e.g. to identify and differentiate between different enum values.
You can use a very nice tool called Stetho
by adding this to build.gradle
file:
compile 'com.facebook.stetho:stetho:1.4.1'
And initialized it inside your Application
or Activity
onCreate()
method:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.activity_main);
}
Then you can view the db records in chrome in the address:
chrome://inspect/#devices
For more details you can read my post: How to view easily your db records
It is not possible to get HTTP Response code by using Selenium WebDriver directly. The code can be got by using Java code and that can be used in Selenium WebDriver.
To get HTTP Response code by java:
public static int getResponseCode(String urlString) throws MalformedURLException, IOException{
URL url = new URL(urlString);
HttpURLConnection huc = (HttpURLConnection)url.openConnection();
huc.setRequestMethod("GET");
huc.connect();
return huc.getResponseCode();
}
Now you can write your Selenium WebDriver code as below:
private static int statusCode;
public static void main(String... args) throws IOException{
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> links = driver.findElements(By.tagName("a"));
for(int i = 0; i < links.size(); i++){
if(!(links.get(i).getAttribute("href") == null) && !(links.get(i).getAttribute("href").equals(""))){
if(links.get(i).getAttribute("href").contains("http")){
statusCode= getResponseCode(links.get(i).getAttribute("href").trim());
if(statusCode == 403){
System.out.println("HTTP 403 Forbidden # " + i + " " + links.get(i).getAttribute("href"));
}
}
}
}
}
The conceptual difference in my understanding it that a project can contain many repo's and that are independent of each other, while simultaneously a repo may contain many projects. Repo's being just a storage place for code while a project being a collection of tasks for a certain feature.
Does that make sense? A large repo can have many projects being worked on by different people at the same time (lots of difference features being added to a monolith), a large project may have many small repos that are separate but part of the same project that interact with each other - microservices? Its a personal take on what you want to do. I think that repo (storage) vs project (tasks) is the main difference - if i am wrong please let me know / explain! Thanks.
The variable name you're looking for is ansible_ssh_private_key_file
.
You should set it at 'vars' level:
in the inventory file:
myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
in the host_vars
:
# hosts_vars/myHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
# hosts_vars/myOtherHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
in a group_vars
file if you use the same key for a group of hosts
in the vars
section of your play:
- hosts: myHost
remote_user: ubuntu
vars_files:
- vars.yml
vars:
ansible_ssh_private_key_file: "{{ key1 }}"
tasks:
- name: Echo a hello message
command: echo hello