The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.
$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString
This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))
If the info does not need to be secure at all you can convert it to plain text:
$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0
ForEach
Loop processes each ZIP file located within the $filepath
variable
foreach($file in $filepath)
{
$zip = $shell.NameSpace($file.FullName)
foreach($item in $zip.items())
{
$shell.Namespace($file.DirectoryName).copyhere($item)
}
Remove-Item $file.FullName
}
I tried the win32com way and xlwings way but I didn't get any luck. I use PyCharm and didn't see the .WorkBook option in the autocompletion for win32com. I got the -2147352567 error when I tried to pass a workbook as variable.
Then, I found a work around using vba shell to run my Python script. Write something on the XLS file you are working with when everything is done. So that Excel knows that it's time to run the VBA macro.
But the vba Application.wait function will take up 100% cpu which is wierd. Some people said that using the windows Sleep function would fix it.
Import xlsxwriter
Shell "C:\xxxxx\python.exe
C:/Users/xxxxx/pythonscript.py"
exitLoop = 0
wait for Python to finish its work.
Do
waitTime = TimeSerial(Hour(Now), Minute(Now), Second(Now) + 30)
Application.Wait waitTime
Set wb2 = Workbooks.Open("D:\xxxxx.xlsx", ReadOnly:=True)
exitLoop = wb2.Worksheets("blablabla").Cells(50, 1)
wb2.Close exitLoop
Loop While exitLoop <> 1
Call VbaScript
You can use:
msiexec /i "c:\package.msi"
You can also add some more optional parameters. There are common msi parameters and parameters which are specific for your installer. For common parameters just call msiexec
If you want to convert CSV to Excel without Excel being installed, you can use the great .NET library EPPlus (under LGPL license) to create and modify Excel Sheets and also convert CSV to Excel really fast!
$HOME\Documents\WindowsPowerShell\Modules\EPPlus
)[Reflection.Assembly]::UnsafeLoadFrom($DLLPath) | Out-Null
# Create temporary CSV and Excel file names
$FileNameCSV = "$HOME\Downloads\test.csv"
$FileNameExcel = "$HOME\Downloads\test.xlsx"
# Create CSV File (with first line containing type information and empty last line)
Get-Process | Export-Csv -Delimiter ';' -Encoding UTF8 -Path $FileNameCSV
# Load EPPlus
$DLLPath = "$HOME\Documents\WindowsPowerShell\Modules\EPPlus\EPPlus.dll"
[Reflection.Assembly]::LoadFile($DLLPath) | Out-Null
# Set CSV Format
$Format = New-object -TypeName OfficeOpenXml.ExcelTextFormat
$Format.Delimiter = ";"
# use Text Qualifier if your CSV entries are quoted, e.g. "Cell1","Cell2"
$Format.TextQualifier = '"'
$Format.Encoding = [System.Text.Encoding]::UTF8
$Format.SkipLinesBeginning = '1'
$Format.SkipLinesEnd = '1'
# Set Preferred Table Style
$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium1
# Create Excel File
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage
$Worksheet = $ExcelPackage.Workbook.Worksheets.Add("FromCSV")
# Load CSV File with first row as heads using a table style
$null=$Worksheet.Cells.LoadFromText((Get-Item $FileNameCSV),$Format,$TableStyle,$true)
# Load CSV File without table style
#$null=$Worksheet.Cells.LoadFromText($file,$format)
# Fit Column Size to Size of Content
$Worksheet.Cells[$Worksheet.Dimension.Address].AutoFitColumns()
# Save Excel File
$ExcelPackage.SaveAs($FileNameExcel)
Write-Host "CSV File $FileNameCSV converted to Excel file $FileNameExcel"
Look for GSpread.NET. You can work with Google Spreadsheets by using API from Microsoft Excel. You don't need to rewrite old code with the new Google API usage. Just add a few row:
Set objExcel = CreateObject("GSpreadCOM.Application");
app.MailLogon(Name, ClientIdAndSecret, ScriptId);
It's an OpenSource project and it doesn't require Office to be installed.
The documentation available over here http://scand.com/products/gspread/index.html
Call the script from a batch file (*.bat) or CMD
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"
pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"
PowerShell
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"
powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"
Call from PowerShell
PowerShell Core or Windows PowerShell
& path-to-script/Script.ps1 -Param1 Hello -Param2 World
& ./Script.ps1 -Param1 Hello -Param2 World
Script.ps1 - Script Code
param(
[Parameter(Mandatory=$True, Position=0, ValueFromPipeline=$false)]
[System.String]
$Param1,
[Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$false)]
[System.String]
$Param2
)
Write-Host $Param1
Write-Host $Param2
I had the same Problem. This solution works for me.
$Word = $null
$Word = [System.Runtime.InteropServices.Marshal]::GetActiveObject('word.application')
if ($Word -eq $null)
{
$Word = new-object -ComObject word.application
}
Microsoft: "Corrupted process state exceptions are exceptions that indicate that the state of a process has been corrupted. We do not recommend executing your application in this state.....If you are absolutely sure that you want to maintain your handling of these exceptions, you must apply the HandleProcessCorruptedStateExceptionsAttribute
attribute"
Microsoft: "Use application domains to isolate tasks that might bring down a process."
The program below will protect your main application/thread from unrecoverable failures without risks associated with use of HandleProcessCorruptedStateExceptions
and <legacyCorruptedStateExceptionsPolicy>
public class BoundaryLessExecHelper : MarshalByRefObject
{
public void DoSomething(MethodParams parms, Action action)
{
if (action != null)
action();
parms.BeenThere = true; // example of return value
}
}
public struct MethodParams
{
public bool BeenThere { get; set; }
}
class Program
{
static void InvokeCse()
{
IntPtr ptr = new IntPtr(123);
System.Runtime.InteropServices.Marshal.StructureToPtr(123, ptr, true);
}
private static void ExecInThisDomain()
{
try
{
var o = new BoundaryLessExecHelper();
var p = new MethodParams() { BeenThere = false };
Console.WriteLine("Before call");
o.DoSomething(p, CausesAccessViolation);
Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); //never stops here
}
catch (Exception exc)
{
Console.WriteLine($"CSE: {exc.ToString()}");
}
Console.ReadLine();
}
private static void ExecInAnotherDomain()
{
AppDomain dom = null;
try
{
dom = AppDomain.CreateDomain("newDomain");
var p = new MethodParams() { BeenThere = false };
var o = (BoundaryLessExecHelper)dom.CreateInstanceAndUnwrap(typeof(BoundaryLessExecHelper).Assembly.FullName, typeof(BoundaryLessExecHelper).FullName);
Console.WriteLine("Before call");
o.DoSomething(p, CausesAccessViolation);
Console.WriteLine("After call. param been there? : " + p.BeenThere.ToString()); // never gets to here
}
catch (Exception exc)
{
Console.WriteLine($"CSE: {exc.ToString()}");
}
finally
{
AppDomain.Unload(dom);
}
Console.ReadLine();
}
static void Main(string[] args)
{
ExecInAnotherDomain(); // this will not break app
ExecInThisDomain(); // this will
}
}
Try using
DateTime.ToOADate()
And putting that as a double in the cell. There could be issues with Excel on Mac Systems (it uses a different datetime-->double conversion), but it should work well for most cases.
Hope this helps.
So far it seems all answers involve some of these:
Which makes me appreciate how difficult this issue is :)
I have been working on a library to simplify access to Excel, and I am trying to make sure that people using it won't leave a mess (fingers crossed).
Instead of writing directly on the interfaces Interop provides, I am making extension methods to make live easier. Like ApplicationHelpers.CreateExcel() or workbook.CreateWorksheet("mySheetNameThatWillBeValidated"). Naturally, anything that is created may lead to an issue later on cleaning up, so I am actually favoring killing the process as last resort. Yet, cleaning up properly (third option), is probably the least destructive and most controlled.
So, in that context I was wondering whether it wouldn't be best to make something like this:
public abstract class ReleaseContainer<T>
{
private readonly Action<T> actionOnT;
protected ReleaseContainer(T releasible, Action<T> actionOnT)
{
this.actionOnT = actionOnT;
this.Releasible = releasible;
}
~ReleaseContainer()
{
Release();
}
public T Releasible { get; private set; }
private void Release()
{
actionOnT(Releasible);
Releasible = default(T);
}
}
I used 'Releasible' to avoid confusion with Disposable. Extending this to IDisposable should be easy though.
An implementation like this:
public class ApplicationContainer : ReleaseContainer<Application>
{
public ApplicationContainer()
: base(new Application(), ActionOnExcel)
{
}
private static void ActionOnExcel(Application application)
{
application.Show(); // extension method. want to make sure the app is visible.
application.Quit();
Marshal.FinalReleaseComObject(application);
}
}
And one could do something similar for all sorts of COM objects.
In the factory method:
public static Application CreateExcelApplication(bool hidden = false)
{
var excel = new ApplicationContainer().Releasible;
excel.Visible = !hidden;
return excel;
}
I would expect that every container will be destructed properly by the GC, and therefore automatically make the call to Quit
and Marshal.FinalReleaseComObject
.
Comments? Or is this an answer to the question of the third kind?
It is Input
and not input
.
This commit removed Input
facade definition from config/app.php
hence you have to manually add that in to aliases
array as below,
'Input' => Illuminate\Support\Facades\Input::class,
Or You can import Input
facade directly as required,
use Illuminate\Support\Facades\Input;
I find the most flexible way to do this is by reading a file in the groovy post build plugin.
import hudson.FilePath
import java.io.InputStream
def build = Thread.currentThread().executable
String unstable = null
if(build.workspace.isRemote()) {
channel = build.workspace.channel;
fp = new FilePath(channel, build.workspace.toString() + "/build.properties")
InputStream is = fp.read()
unstable = is.text.trim()
} else {
fp = new FilePath(new File(build.workspace.toString() + "/build.properties"))
InputStream is = fp.read()
unstable = is.text.trim()
}
manager.listener.logger.println("Build status file: " + unstable)
if (unstable.equalsIgnoreCase('true')) {
manager.listener.logger.println('setting build to unstable')
manager.buildUnstable()
}
If the file contents are 'true' the build will be set to unstable. This will work on the local master and on any slaves you run the job on, and for any kind of scripts that can write to disk.
Follow the below steps to show the name of the branch of your GIT repo in ubuntu terminal:
step1: open terminal and edit .bashrc using the following command.
vi .bashrc
step2: add the following line at the end of the .bashrc file :
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' }
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
step3: source .bashrc in the root (home) directory by doing:
/rootfolder:~$ source .bashrc
Step4: Restart and open the terminal and check the cmd. Navigate to your GIt repo directory path and you are done. :)
a = a.split("\n");
Note that split
ting returns the new array, rather than just assigning it to the original string. You need to explicitly store it in a variable.
2 options I know of.
These wont give you C# though.
The Right solution is to Change a property in XML under your Activity tag to below style. It just works
android:theme="@style/Theme.AppCompat.Light.NoActionBar"
There's a description of how to do this at Resize a column in a PostgreSQL table without changing data. You have to hack the database catalog data. The only way to do this officially is with ALTER TABLE, and as you've noted that change will lock and rewrite the entire table while it's running.
Make sure you read the Character Types section of the docs before changing this. All sorts of weird cases to be aware of here. The length check is done when values are stored into the rows. If you hack a lower limit in there, that will not reduce the size of existing values at all. You would be wise to do a scan over the whole table looking for rows where the length of the field is >40 characters after making the change. You'll need to figure out how to truncate those manually--so you're back some locks just on oversize ones--because if someone tries to update anything on that row it's going to reject it as too big now, at the point it goes to store the new version of the row. Hilarity ensues for the user.
VARCHAR is a terrible type that exists in PostgreSQL only to comply with its associated terrible part of the SQL standard. If you don't care about multi-database compatibility, consider storing your data as TEXT and add a constraint to limits its length. Constraints you can change around without this table lock/rewrite problem, and they can do more integrity checking than just the weak length check.
You can use forEach starting from Java 8:
List<String> nameList = new ArrayList<>(
Arrays.asList("USA", "USSR", "UK"));
nameList.forEach((v) -> System.out.println(v));
In Swift We Can Make A button programmatically by writing this code in our viewcontroller.swift file...
import UIKit
class ViewController: UIViewController
{
private let firstbutton:UIButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.firstbutton = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton
self.firstbutton!.frame = CGRectMake(100, 200, 100, 100)
self.firstbutton!.backgroundColor = UIColor.redColor()
self.firstbutton!.setTitle("My Button", forState: UIControlState.Normal)
self.firstbutton!.addTarget(self, action:#selector(self.firstButtonClicked), forControlEvents: .TouchUpInside)
self.view.addSubview(firstbutton!)
}
func firstButtonClicked(){
print("First Button Clicked")
}
As user1767754 said, the key here is to not make any selection initially.
Just place the cursor inside the variable name, don't double click to select it. For single character variables, place the cursor at the front or end of the variable to not make any selection initially.
Now keep hitting Cmd+D for next variable selection or Ctrl+Cmd+G for selecting all variables at once. It will magically select only the variables.
My tested version
Sub PrintArray(RowPrint, ColPrint, ArrayName, WorkSheetName)
Sheets(WorkSheetName).Range(Cells(RowPrint, ColPrint), _
Cells(RowPrint + UBound(ArrayName, 2) - 1, _
ColPrint + UBound(ArrayName, 1) - 1)) = _
WorksheetFunction.Transpose(ArrayName)
End Sub
This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level
You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property
You can do that by following steps:
If you need to rename not all but multiple column at once when you only know the old column names you can use colnames
function and %in%
operator. Example:
df = data.frame(bad=1:3, worse=rnorm(3), worst=LETTERS[1:3])
bad worse worst
1 1 -0.77915455 A
2 2 0.06717385 B
3 3 -0.02827242 C
Now you want to change "bad" and "worst" to "good" and "best". You can use
colnames(df)[which(colnames(df) %in% c("bad","worst") )] <- c("good","best")
This results in
good worse best
1 1 -0.6010363 A
2 2 0.7336155 B
3 3 0.9435469 C
You don't need ANY of these other fancy answers. Below is a simplistic example that doesn't have all the Margin
, Height
, Width
properties set in the XAML, but should be enough to show how to get this done at a basic level.
XAML
Build a Window
page like you would normally and add your fields to it, say a Label
and TextBox
control inside a StackPanel
:
<StackPanel Orientation="Horizontal">
<Label Name="lblUser" Content="User Name:" />
<TextBox Name="txtUser" />
</StackPanel>
Then create a standard Button
for Submission ("OK" or "Submit") and a "Cancel" button if you like:
<StackPanel Orientation="Horizontal">
<Button Name="btnSubmit" Click="btnSubmit_Click" Content="Submit" />
<Button Name="btnCancel" Click="btnCancel_Click" Content="Cancel" />
</StackPanel>
Code-Behind
You'll add the Click
event handler functions in the code-behind, but when you go there, first, declare a public variable where you will store your textbox value:
public static string strUserName = String.Empty;
Then, for the event handler functions (right-click the Click
function on the button XAML, select "Go To Definition", it will create it for you), you need a check to see if your box is empty. You store it in your variable if it is not, and close your window:
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
strUserName = txtUser.Text;
this.Close();
}
else
MessageBox.Show("Must provide a user name in the textbox.");
}
Calling It From Another Page
You're thinking, if I close my window with that this.Close()
up there, my value is gone, right? NO!! I found this out from another site: http://www.dreamincode.net/forums/topic/359208-wpf-how-to-make-simple-popup-window-for-input/
They had a similar example to this (I cleaned it up a bit) of how to open your Window
from another and retrieve the values:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
MyPopupWindow popup = new MyPopupWindow(); // this is the class of your other page
//ShowDialog means you can't focus the parent window, only the popup
popup.ShowDialog(); //execution will block here in this method until the popup closes
string result = popup.strUserName;
UserNameTextBlock.Text = result; // should show what was input on the other page
}
}
Cancel Button
You're thinking, well what about that Cancel button, though? So we just add another public variable back in our pop-up window code-behind:
public static bool cancelled = false;
And let's include our btnCancel_Click
event handler, and make one change to btnSubmit_Click
:
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
cancelled = true;
strUserName = String.Empty;
this.Close();
}
private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(txtUser.Text))
{
strUserName = txtUser.Text;
cancelled = false; // <-- I add this in here, just in case
this.Close();
}
else
MessageBox.Show("Must provide a user name in the textbox.");
}
And then we just read that variable in our MainWindow
btnOpenPopup_Click
event:
private void btnOpenPopup_Click(object sender, RoutedEventArgs e)
{
MyPopupWindow popup = new MyPopupWindow(); // this is the class of your other page
//ShowDialog means you can't focus the parent window, only the popup
popup.ShowDialog(); //execution will block here in this method until the popup closes
// **Here we find out if we cancelled or not**
if (popup.cancelled == true)
return;
else
{
string result = popup.strUserName;
UserNameTextBlock.Text = result; // should show what was input on the other page
}
}
Long response, but I wanted to show how easy this is using public static
variables. No DialogResult
, no returning values, nothing. Just open the window, store your values with the button events in the pop-up window, then retrieve them afterwards in the main window function.
Write a script with two curl requests in desired order and run it by cron, like
#!/bin/bash
curl http://mysite.com/?update_=1
curl http://mysite.com/?the_other_thing
test[,sort(names(test))]
sort on names of columns can work easily.
The best solution is to use async Task
. You should avoid async void
for several reasons, one of which is composability.
If the method cannot be made to return Task
(e.g., it's an event handler), then you can use SemaphoreSlim
to have the method signal when it is about to exit. Consider doing this in a finally
block.
The 2018 ES6+ ANSWER IS:
const arr = [1, 2, 3];
arr.forEach((val, key, arr) => {
if (Object.is(arr.length - 1, key)) {
// execute last item logic
console.log(`Last callback call at index ${key} with value ${val}` );
}
});
Had the same error. Removing the object from the model did the trick.
Code which shows the mistake:
void update() {
VBox vBox = mHboxEventSelection.getVboxSelectionRows();
Session session = HibernateUtilEventsCreate.getSessionFactory().openSession();
session.beginTransaction();
HashMap<String, EventLink> existingEventLinks = new HashMap<>();
for (EventLink eventLink : mEventProperty.getEventLinks()) {
existingEventLinks.put(eventLink.getEvent().getName(), eventLink);
}
mEventProperty.setName(getName());
for (Node node : vBox.getChildren()) {
if (node instanceof HBox) {
JFXComboBox<EventEntity> comboBoxEvents = (JFXComboBox<EventEntity>) ((HBox) node).getChildren().get(0);
if (comboBoxEvents.getSelectionModel().getSelectedIndex() == -1) {
Log.w(TAG, "update: Invalid eventEntity collection");
}
EventEntity eventEntity = comboBoxEvents.getSelectionModel().getSelectedItem();
Log.v(TAG, "update(" + mCostType + "): event-id=" + eventEntity.getId() + " - " + eventEntity.getName());
String split = ((JFXTextField) (((HBox) node).getChildren().get(1))).getText();
if (split.isEmpty()) {
split = "0";
}
if (existingEventLinks.containsKey(eventEntity.getName())) {
// event-link did exist
EventLink eventLink = existingEventLinks.get(eventEntity.getName());
eventLink.setSplit(Integer.parseInt(split));
session.update(eventLink);
existingEventLinks.remove(eventEntity.getName(), eventLink);
} else {
// event-link is a new one, so create!
EventLink link1 = new EventLink();
link1.setProperty(mEventProperty);
link1.setEvent(eventEntity);
link1.setCreationTime(new Date(System.currentTimeMillis()));
link1.setSplit(Integer.parseInt(split));
eventEntity.getEventLinks().add(link1);
session.saveOrUpdate(eventEntity);
}
}
}
for (Map.Entry<String, EventLink> entry : existingEventLinks.entrySet()) {
Log.i(TAG, "update: will delete link=" + entry.getKey());
EventLink val = entry.getValue();
mEventProperty.getEventLinks().remove(val); // <- remove from model
session.delete(val);
}
session.saveOrUpdate(mEventProperty);
session.getTransaction().commit();
session.close();
}
Assuming you will get the date string in a proper format, I have a solution.
function parseDateTime(dt) {
var date = false;
if (dt) {
var c_date = new Date(dt);
var hrs = c_date.getHours();
var min = c_date.getMinutes();
if (isNaN(hrs) || isNaN(min) || c_date === "Invalid Date") {
return null;
}
var type = (hrs <= 12) ? " AM" : " PM";
date = ((+hrs % 12) || hrs) + ":" + min + type;
}
return date;
}
parseDateTime("2016-11-21 12:39:08");//"12:39 AM"
parseDateTime("2017-11-21 23:39:08");//"11:39 PM"
Spring has some standard events which you can handle.
To do that, you must create and register a bean that implements the ApplicationListener
interface, something like this:
package test.pack.age;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class ApplicationListenerBean implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
// now you can do applicationContext.getBean(...)
// ...
}
}
}
You then register this bean within your servlet.xml
or applicationContext.xml
file:
<bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />
and Spring will notify it when the application context is initialized.
In Spring 3 (if you are using this version), the ApplicationListener
class is generic and you can declare the event type that you are interested in, and the event will be filtered accordingly. You can simplify a bit your bean code like this:
public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
ApplicationContext applicationContext = event.getApplicationContext();
// now you can do applicationContext.getBean(...)
// ...
}
}
$( "#btnAddProfile" ).on( "click",function(event){
$( event.target ).html( "Save" );
});
What is the difference?
From the documentation:
- - (Boolean)
instance_of?(class)
- Returns
true
ifobj
is an instance of the given class.
and:
- - (Boolean)
is_a?(class)
- (Boolean)kind_of?(class)
- Returns
true
ifclass
is the class ofobj
, or ifclass
is one of the superclasses ofobj
or modules included inobj
.
If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.
When should I use which?
Never. Use polymorphism instead.
Why are there so many of them?
I wouldn't call two "many". There are two of them, because they do two different things.
On the side note: if you have all of the files locally (not only wsdl file but also xsd files) you can invoke wsdl.exe in that manner:
wsdl.exe [path to your wsdl file] [paths to xsd files imported by wsdl]
That way wsdl.exe can resolve all dependecies locally and correctly generates proxy class.
Maybe it will save somebody some time - it solves "missing type" error when service is not avaliable online.
See for a comparison of net-ioc-frameworks on google code including linfu and spring.net that are not on your list while i write this text.
I worked with spring.net: It has many features (aop, libraries , docu, ...) and there is a lot of experience with it in the dotnet and the java-world. The features are modularized so you donot have to take all features. The features are abstractions of common issues like databaseabstraction, loggingabstraction. however it is difficuilt to do and debug the IoC-configuration.
From what i have read so far: If i had to chooseh for a small or medium project i would use ninject since ioc-configuration is done and debuggable in c#. But i havent worked with it yet. for large modular system i would stay with spring.net because of abstraction-libraries.
In C int foo()
and int foo(void)
are different functions. int foo()
accepts an arbitrary number of arguments, while int foo(void)
accepts 0 arguments. In C++ they mean the same thing. I suggest that you use void
consistently when you mean no arguments.
If you have a variable a
, extern int a;
is a way to tell the compiler that a
is a symbol that might be present in a different translation unit (C compiler speak for source file), don't resolve it until link time. On the other hand, symbols which are function names are anyway resolved at link time. The meaning of a storage class specifier on a function (extern
, static
) only affects its visibility and extern
is the default, so extern
is actually unnecessary.
I suggest removing the extern
, it is extraneous and is usually omitted.
I have the same problem. I try to present view controller just after dismissing.
[self dismissModalViewControllerAnimated:YES];
When I try to do it without animation it works perfectly so the problem is that controller is still alive. I think that the best solution is to use dismissViewControllerAnimated:completion:
for iOS5
Thanks to Camilo Martin, I was able to answer a related question:
What I wanted to do was
find ... -exec zcat {} | wc -l \;
which didn't work. However,
find ... | while read -r file; do echo "$file: `zcat $file | wc -l`"; done
does work, so thank you!
var newItem = document.createElement("LI"); // Create a <li> node
var textnode = document.createTextNode("Water"); // Create a text node
newItem.appendChild(textnode); // Append the text to <li>
var list = document.getElementById("myList"); // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]); // Insert <li> before the first child of <ul>
let's say you write your script.rb
script. put:
#!/usr/bin/env ruby
as the first line and do a chmod +x script.rb
It can also happen with varchar2 columns. This is pretty reproducible with PreparedStatements through JDBC by simply
So as above said it can be wrong with types, or column width exceeded.
Also note that as varchar2 allows 4k chars max, the real limit will be 2k for double byte chars
Hope this helps
As an addition to Jakub's answer, if you plan to use JavaConfig, you can also autowire that way:
import com.google.common.collect.Lists;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
<...>
@Configuration
public class MyConfiguration {
@Bean
public List<Stage> stages(final Stage1 stage1, final Stage2 stage2) {
return Lists.newArrayList(stage1, stage2);
}
}
One function can do the job,
void free_list(node *pHead)
{
node *pNode = pHead, *pNext;
while (NULL != pNode)
{
pNext = pNode->next;
free(pNode);
pNode = pNext;
}
}
Here's an example which issues the same warning:
import numpy as np
np.seterr(all='warn')
A = np.array([10])
a=A[-1]
a**a
yields
RuntimeWarning: overflow encountered in long_scalars
In the example above it happens because a
is of dtype int32
, and the maximim value storable in an int32
is 2**31-1. Since 10**10 > 2**32-1
, the exponentiation results in a number that is bigger than that which can be stored in an int32
.
Note that you can not rely on np.seterr(all='warn')
to catch all overflow
errors in numpy. For example, on 32-bit NumPy
>>> np.multiply.reduce(np.arange(21)+1)
-1195114496
while on 64-bit NumPy:
>>> np.multiply.reduce(np.arange(21)+1)
-4249290049419214848
Both fail without any warning, although it is also due to an overflow error. The correct answer is that 21! equals
In [47]: import math
In [48]: math.factorial(21)
Out[50]: 51090942171709440000L
According to numpy developer, Robert Kern,
Unlike true floating point errors (where the hardware FPU sets a flag whenever it does an atomic operation that overflows), we need to implement the integer overflow detection ourselves. We do it on the scalars, but not arrays because it would be too slow to implement for every atomic operation on arrays.
So the burden is on you to choose appropriate dtypes
so that no operation overflows.
Several of the responses rely on an exception being thrown and having it handled in the OnException override. In my case, I wanted to return statuses such as bad request if the user, say, had passed in a bad ID. What works for me is to use the ControllerContext:
var jsonResult = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = "whoops" };
ControllerContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
return jsonResult;
If you have background on that element, then, adding padding would be useless.
So, in this case, you can use background-clip: content-box; or outline-offset
Explanation: If you use wrapper, then it would be simple to separate the background from border. But if you want to style the same element, which has a background, no matter how much padding you would add, there would be no space between background and border, unless you use background-clip or outline-offset
Just do the following change
echo off
cls
echo Would you like to do a backup?
pause
copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER
pause
While you have a return value in checkform, it isn't being used anywhere - try using onclick="return checkform()"
instead.
You may want to considering replacing this method with onsubmit="return checkform()"
in the form tag instead, though both will work for clicking the button.
Try changing the port to 465
mail.smtp.socketFactory.port=465
mail.smtp.port=465
select into
is used in pl/sql to set a variable to field values. Instead, use
create table new_table as select * from old_table
You can define more details by extending AbstractMongoConfiguration.
@Configuration
@EnableMongoRepositories("demo.mongo.model")
public class SpringMongoConfig extends AbstractMongoConfiguration {
@Value("${spring.profiles.active}")
private String profileActive;
@Value("${spring.application.name}")
private String proAppName;
@Value("${spring.data.mongodb.host}")
private String mongoHost;
@Value("${spring.data.mongodb.port}")
private String mongoPort;
@Value("${spring.data.mongodb.database}")
private String mongoDB;
@Override
public MongoMappingContext mongoMappingContext()
throws ClassNotFoundException {
// TODO Auto-generated method stub
return super.mongoMappingContext();
}
@Override
@Bean
public Mongo mongo() throws Exception {
return new MongoClient(mongoHost + ":" + mongoPort);
}
@Override
protected String getDatabaseName() {
// TODO Auto-generated method stub
return mongoDB;
}
}
Assuming you have access to LINQ, and Age
is an int
(you may also try var maxAge
- it is more likely to compile):
int maxAge = myTypes.Max(t => t.Age);
If you also need the RandomID
(or the whole object), a quick solution is to use MaxBy
from MoreLinq
MyType oldest = myTypes.MaxBy(t => t.Age);
Below is example you can use:
create temp table test2 (
id1 numeric,
id2 numeric,
id3 numeric,
id4 numeric,
id5 numeric,
id6 numeric,
id7 numeric,
id8 numeric,
id9 numeric,
id10 numeric)
with (oids = false);
do
$do$
declare
i int;
begin
for i in 1..100000
loop
insert into test2 values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;
If this happened to you after renaming your application package name, then you need to update the following:
1)google-services.json file in your application by looking up in the file for "package_name" attribute and update it with the new package name.
2)Update your application client Credentials in Google Developers Console by going to the Credentials
and selecting your android client key then update the package name as well with the new one.
Hope this will help.
Find extension=php_soap.dll
or extension=soap
in php.ini and remove the commenting semicolon at the beginning of the line. Eventually check for soap.ini
under the conf.d directory.
Restart your server.
Apache
sudo apt-get install php7.0-soap
sudo systemctl restart apache2
PHP5
sudo apt-get install php-soap
sudo systemctl restart apache2
Apache
sudo zypper in php7-soap
sudo systemctl restart apache2
Nginx
sudo zypper in php7-soap
sudo systemctl restart nginx
Just implemented my OWIN Service with Bearer (called access_token in the following) and Refresh Tokens. My insight into this is that you can use different flows. So it depends on the flow you want to use how you set your access_token and refresh_token expiration times.
I will describe two flows A and B in the follwing (I suggest what you want to have is flow B):
A) expiration time of access_token and refresh_token are the same as it is per default 1200 seconds or 20 minutes. This flow needs your client first to send client_id and client_secret with login data to get an access_token, refresh_token and expiration_time. With the refresh_token it is now possible to get a new access_token for 20 minutes (or whatever you set the AccessTokenExpireTimeSpan in the OAuthAuthorizationServerOptions to). For the reason that the expiration time of access_token and refresh_token are the same, your client is responsible to get a new access_token before the expiration time! E.g. your client could send a refresh POST call to your token endpoint with the body (remark: you should use https in production)
grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxx
to get a new token after e.g. 19 minutes to prevent the tokens from expiration.
B) in this flow you want to have a short term expiration for your access_token and a long term expiration for your refresh_token. Lets assume for test purpose you set the access_token to expire in 10 seconds (AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(10)
) and the refresh_token to 5 Minutes. Now it comes to the interesting part setting the expiration time of refresh_token: You do this in your createAsync function in SimpleRefreshTokenProvider class like this:
var guid = Guid.NewGuid().ToString();
//copy properties and set the desired lifetime of refresh token
var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
{
IssuedUtc = context.Ticket.Properties.IssuedUtc,
ExpiresUtc = DateTime.UtcNow.AddMinutes(5) //SET DATETIME to 5 Minutes
//ExpiresUtc = DateTime.UtcNow.AddMonths(3)
};
/*CREATE A NEW TICKET WITH EXPIRATION TIME OF 5 MINUTES
*INCLUDING THE VALUES OF THE CONTEXT TICKET: SO ALL WE
*DO HERE IS TO ADD THE PROPERTIES IssuedUtc and
*ExpiredUtc to the TICKET*/
var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);
//saving the new refreshTokenTicket to a local var of Type ConcurrentDictionary<string,AuthenticationTicket>
// consider storing only the hash of the handle
RefreshTokens.TryAdd(guid, refreshTokenTicket);
context.SetToken(guid);
Now your client is able to send a POST call with a refresh_token to your token endpoint when the access_token
is expired. The body part of the call may look like this: grant_type=refresh_token&client_id=xxxxxx&refresh_token=xxxxxxxx-xxxx-xxxx-xxxx-xx
One important thing is that you may want to use this code not only in your CreateAsync function but also in your Create function. So you should consider to use your own function (e.g. called CreateTokenInternal) for the above code. Here you can find implementations of different flows including refresh_token flow(but without setting the expiration time of the refresh_token)
Here is one sample implementation of IAuthenticationTokenProvider on github (with setting the expiration time of the refresh_token)
I am sorry that I can't help out with further materials than the OAuth Specs and the Microsoft API Documentation. I would post the links here but my reputation doesn't let me post more than 2 links....
I hope this may help some others to spare time when trying to implement OAuth2.0 with refresh_token expiration time different to access_token expiration time. I couldn't find an example implementation on the web (except the one of thinktecture linked above) and it took me some hours of investigation until it worked for me.
New info: In my case I have two different possibilities to receive tokens. One is to receive a valid access_token. There I have to send a POST call with a String body in format application/x-www-form-urlencoded with the following data
client_id=YOURCLIENTID&grant_type=password&username=YOURUSERNAME&password=YOURPASSWORD
Second is if access_token is not valid anymore we can try the refresh_token by sending a POST call with a String body in format application/x-www-form-urlencoded
with the following data grant_type=refresh_token&client_id=YOURCLIENTID&refresh_token=YOURREFRESHTOKENGUID
You can modify the id
without having to use getElementById
Example:
<div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>
You can see it here: http://jsbin.com/elikaj/1/
Tested with Mozilla Firefox 22 and Google Chrome 60.0
First of all, goto extensions (Ctrl + Shift + X) and install 2 extensions:
Then, then reload the VS Code and select a play button on the top of the right corner your program runs in the output terminal. You can see output by Ctrl + Alt + N. To change other features goto user setting.
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy import excel file to sql server database using SqlBulkCopy. It uses small memory because it reads by SAX(Simple API for XML) method (OpenXmlReader)
Example:
private static void DataReaderBulkCopySample()
{
using (var reader = new ExcelDataReader(@"test.xlsx"))
{
var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();
DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols);
using (var bulkCopy = new SqlBulkCopy(ConnectionString))
{
// MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess,
// optimizing memory usage by using the IDataReader streaming capabilities
bulkCopy.EnableStreaming = true;
bulkCopy.DestinationTableName = TableName;
foreach (var col in cols)
bulkCopy.ColumnMappings.Add(col, col);
bulkCopy.WriteToServer(reader);
}
}
}
You'll have to convert it from dps to pixels using the display scale factor.
final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);
This is documented on ?logical
. The pertinent section of which is:
Details:
‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
in the R language, whereas ‘T’ and ‘F’ are global variables whose
initial values set to these. All four are ‘logical(1)’ vectors.
Logical vectors are coerced to integer vectors in contexts where a
numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.
The second paragraph there explains the behaviour you are seeing, namely 5 == 1L
and 5 == 0L
respectively, which should both return FALSE
, where as 1 == 1L
and 0 == 0L
should be TRUE for 1 == TRUE
and 0 == FALSE
respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE
and FALSE
in R, i.e. what numeric values they take when coerced to numeric.
However, only TRUE
is guaranteed to the be TRUE
:
> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE
isTRUE
is a wrapper for identical(x, TRUE)
, and from ?isTRUE
we note:
Details:
....
‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
true if and only if ‘x’ is a length-one logical vector whose only
element is ‘TRUE’ and which has no attributes (not even names).
So by the same virtue, only FALSE
is guaranteed to be exactly equal to FALSE
.
> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE
If this concerns you, always use isTRUE()
or identical(x, FALSE)
to check for equivalence with TRUE
and FALSE
respectively. ==
is not doing what you think it is.
had better be
List
The only List
implementation in java.util.concurrent
is CopyOnWriteArrayList. There's also the option of a synchronized list as Travis Webb mentions.
That said, are you sure you need it to be a List
? There are a lot more options for concurrent Queue
s and Map
s (and you can make Set
s from Map
s), and those structures tend to make the most sense for many of the types of things you want to do with a shared data structure.
For queues, you have a huge number of options and which is most appropriate depends on how you need to use it:
Why not just try this:
right click on the table -> Script Table As -> Create To -> New Query Editor Window?
The entire list of columns are given in the script. Copy it and use the fields as necessary.
<c:if test="${ansokanInfo.pSystem eq 'NAT'}">
hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/
with pause functionality on mouseover: http://jsfiddle.net/zrW5q/
hope this helps, have a nice one, cheers!
html
<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>?
Jquery code
(function($) {
$.fn.textWidth = function(){
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent' : that.css('text-indent'),
'overflow' : that.css('overflow'),
'white-space' : that.css('white-space')
},
marqueeCss = {
'text-indent' : width,
'overflow' : 'hidden',
'white-space' : 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
i = 0,
stop = textWidth*-1,
dfd = $.Deferred();
function go() {
if(!that.length) return dfd.reject();
if(width == stop) {
i++;
if(i == args.count) {
that.css(css);
return dfd.resolve();
}
if(args.leftToRight) {
width = textWidth*-1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if(args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if(args.leftToRight) {
width = textWidth*-1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
})(jQuery);
$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })?
Try this way
public void average(int[] data) {
int sum = 0;
double average;
for(int i=0; i < data.length; i++){
sum = sum + data[i];
}
average = (double)sum/data.length;
System.out.println("Average value of array element is " + average);
}
if you need to return average value you need to use double key word Instead of the void key word and need to return value return average.
public double average(int[] data) {
int sum = 0;
double average;
for(int i=0; i < data.length; i++){
sum = sum + data[i];
}
average = (double)sum/data.length;
return average;
}
Having just messed around with this, it's useful to kjnow that the e.X / e.Y points are relative to the control, so if (as I was) you are adding a context menu to a listview or something similar, you will want to adjust it with the form's origin. In the example below I've added 20 to the x/y so that the menu appears slightly to the right and under the cursor.
cmDelete.Show(this, new Point(e.X + ((Control)sender).Left+20, e.Y + ((Control)sender).Top+20));
echo Hello, > file.txt
echo. >>file.txt
echo world >>file.txt
and you can always run:
wordpad file.txt
on any version of Windows.
On Windows 2000 and above you can do:
( echo Hello, & echo. & echo world ) > file.txt
Another way of showing a message for a small amount of text is to create file.vbs containing:
Msgbox "Hello," & vbCrLf & vbCrLf & "world", 0, "Message"
Call it with
cscript /nologo file.vbs
Or use wscript
if you don't need it to wait until they click OK.
The problem with the message you're writing is that the vertical bar (|
) is the "pipe" operator. You'll need to escape it by using ^|
instead of |
.
P.S. it's spelled Pwned.
Is this what you need?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp" >
<ImageView
android:id="@+id/place_category_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:contentDescription="ss"
android:paddingRight="15dp"
android:paddingTop="10dp"
android:src="@drawable/marker" />
<TextView
android:id="@+id/place_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Place Name"
android:textColor="#F00F00"
android:layout_gravity="center_vertical"
android:textSize="14sp"
android:textStyle="bold" />
<TextView
android:id="@+id/place_distance"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:layout_gravity="center_vertical"
android:text="320" />
</TableRow>
</RelativeLayout>
sqsh (http://www.sqsh.org/) + freetds (http://www.freetds.org)
sqsh was primarily an isql replacement for Sybase SQL Server (now ASE) but it works just fine for connecting to SQL Server (provided you use freetds).
To compile, simply point $SYBASE to freetds install and it should work from there. I use it on my Mac all day.
The best part of sqsh are the advanced features, such as dead simple server linking (no need to set up linked servers in SQL Server), flow control and looping (no more concatenating strings and executing dynamic SQL), and invisible bulk copy/load.
Anyone who uses any other command line tool is simply crazy! :)
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
I found an even elegant and simple solution to clearing cache
WebView obj;
obj.clearCache(true);
http://developer.android.com/reference/android/webkit/WebView.html#clearCache%28boolean%29
I have been trying to figure out the way to clear the cache, but all we could do from the above mentioned methods was remove the local files, but it never clean the RAM.
The API clearCache, frees up the RAM used by the webview and hence mandates that the webpage be loaded again.
here is what i came up with. combining multiple answers
#computer list below
$computers = (
'computer1.domain.local',
'computer2.domain.local'
)
foreach ($Computer in $computers) {
Invoke-Command -ComputerName $Computer -ScriptBlock {
Write-Host '______ '$Env:Computername
$usertocheck = 'SomeUserName'
$sessionID = ((quser | Where-Object { $_ -match $usertocheck }) -split ' +')[2]
If([string]::IsNullOrEmpty($sessionID)){
Write-Host -ForegroundColor Yellow "User Not Found."
} else {
write-host -ForegroundColor Green 'Logging off ' $usertocheck 'Session ID' $sessionID
logoff $sessionID
}
}
}
Couldn't get anyone of these working so will add my one just in-case it helps.
public class MyEditTextDatePicker implements OnClickListener, OnDateSetListener {
EditText _editText;
private int _day;
private int _month;
private int _birthYear;
private Context _context;
public MyEditTextDatePicker(Context context, int editTextViewID)
{
Activity act = (Activity)context;
this._editText = (EditText)act.findViewById(editTextViewID);
this._editText.setOnClickListener(this);
this._context = context;
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
_birthYear = year;
_month = monthOfYear;
_day = dayOfMonth;
updateDisplay();
}
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
DatePickerDialog dialog = new DatePickerDialog(_context, this,
calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
dialog.show();
}
// updates the date in the birth date EditText
private void updateDisplay() {
_editText.setText(new StringBuilder()
// Month is 0 based so add 1
.append(_day).append("/").append(_month + 1).append("/").append(_birthYear).append(" "));
}
}
Also something that isn't mentioned in the others. Make sure you put the following on EditText xml.
android:focusable="false"
Otherwise like in my case the Keyboard will keep popping up. Hope this helps someone
From one of my other posts, getting a unixtimestamp:
$unixTimestamp = time();
Converting to mysql datetime format:
$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);
Getting some mysql timestamp:
$mysqlTimestamp = '2013-01-10 12:13:37';
Converting it to a unixtimestamp:
$unixTimestamp = strtotime('2010-05-17 19:13:37');
...comparing it with one or a range of times, to see if the user entered a realistic time:
if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}
Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:
if(ctype_digit($_GET["UpdateTimestamp"]))
{...}
ANT_HOME
is not being resolved. Change %ANT_HOME%\bin
in the Path system environment variable to c:\apache-ant\apache-ant-1.8.2\bin
.
Q1.) Assuming process B tries to take ownership of the same mutex you locked in process A (you left that out of your pseudocode) then no, process B cannot access sharedResource while the mutex is locked since it will sit waiting to lock the mutex until it is released by process A. It will return from the mutex_lock() function when the mutex is locked (or when an error occurs!)
Q2.) In Process B, ensure you always lock the mutex, access the shared resource, and then unlock the mutex. Also, check the return code from the mutex_lock( pMutex ) routine to ensure that you actually own the mutex, and ONLY unlock the mutex if you have locked it. Do the same from process A.
Both processes should basically do the same thing when accessing the mutex.
lock()
If the lock succeeds, then {
access sharedResource
unlock()
}
Q3.) Yes, there are lots of diagrams: =) https://www.google.se/search?q=mutex+thread+process&rlz=1C1AFAB_enSE487SE487&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&ei=ErodUcSmKqf54QS6nYDoAw&biw=1200&bih=1730&sei=FbodUbPbB6mF4ATarIBQ
overflow: scroll;
-webkit-overflow-scrolling: touch;
On container you can set bounce effect inside element
Source: http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/
I'm surprised no one has mentioned Microsoft's ildasm. It may not be as pretty as ILSpy or Reflector, but it comes with Visual Studio so many developers already have it.
To run it (assuming VS 2013, should be similar for other versions):
Now you can navigate the DLL structure. Double-click on class members to see the IL. Use File > Dump to export IL to a file.
I find accepted answer (Serj-Tm) most robust, but I'd like to suggest a generic version.
public static List<List<T>> splitList<T>(List<T> locations, int nSize = 30)
{
var list = new List<List<T>>();
for (int i = 0; i < locations.Count; i += nSize)
{
list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i)));
}
return list;
}
I know this question is really old but I think there's a better way of doing this
#include <string>
#include <sstream>
bool string_to_int(std::string value, int * result) {
std::stringstream stream1, stream2;
std::string stringednumber;
int tempnumber;
stream1 << value;
stream1 >> tempnumber;
stream2 << tempnumber;
stream2 >> stringednumber;
if (!value.compare(stringednumber)) {
*result = tempnumber;
return true;
}
else return false;
}
If I wrote the code right, this will return a boolean value that tells you if the string was a valid number, if false, it wasn't a number, if true it was a number and that number is now result, you would call this this way:
std::string input;
std::cin >> input;
bool worked = string_to_int(input, &result);
For a one-page web application where I add scrollable sections dynamically, I trigger OSX's scrollbars by programmatically scrolling one pixel down and back up:
// Plain JS:
var el = document.getElementById('scrollable-section');
el.scrollTop = 1;
el.scrollTop = 0;
// jQuery:
$('#scrollable-section').scrollTop(1).scrollTop(0);
This triggers the visual cue fading in and out.
For me it worked to stash save all the changes before the commit and pop them out again. This made git re-analyze the added / deleted files and it correctly marked them as moved.
Final cannot be applied to non-virtual functions.
error: only virtual member functions can be marked 'final'
It wouldn't be very meaningful to be able to mark a non-virtual method as 'final'. Given
struct A { void foo(); };
struct B : public A { void foo(); };
A * a = new B;
a -> foo(); // this will call A :: foo anyway, regardless of whether there is a B::foo
a->foo()
will always call A::foo
.
But, if A::foo was virtual
, then B::foo would override it. This might be undesirable, and hence it would make sense to make the virtual function final.
The question is though, why allow final on virtual functions. If you have a deep hierarchy:
struct A { virtual void foo(); };
struct B : public A { virtual void foo(); };
struct C : public B { virtual void foo() final; };
struct D : public C { /* cannot override foo */ };
Then the final
puts a 'floor' on how much overriding can be done. Other classes can extend A and B and override their foo
, but it a class extends C then it is not allowed.
So it probably doesn't make sense to make the 'top-level' foo final
, but it might make sense lower down.
(I think though, there is room to extend the words final and override to non-virtual members. They would have a different meaning though.)
You mean the tellItLikeItIs
method? Yes, you have to specify void
to specify that the method doesn't return anything. All methods have to have a return type specified, even if it's void
.
It certainly doesn't return a string - look, there are no return statements anywhere. It's not really clear why you think it is returning a string. It's printing strings to the console, but that's not the same thing as returning one from the method.
If you are asking whether there is a built in Pythonic range
-like function, there isn't. You have to do it the brute force way. Maybe rangy would be of interest to you.
Just a different version of adding a month and subtracting a day for creating reports:
ex: StartofMonth is '2019-10-01'
dateadd(day,-1,dateadd(month,1,StartofMonth))
EndOfMonth will become '2019-10-31'
Here is a solution I made using the above ideas that can be used for TextBoxFor and PasswordFor:
public static class HtmlHelperEx
{
public static MvcHtmlString TextBoxWithPlaceholderFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return htmlHelper.TextBoxFor(expression, htmlAttributes.AddAttribute("placeholder", metadata.Watermark));
}
public static MvcHtmlString PasswordWithPlaceholderFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
return htmlHelper.PasswordFor(expression, htmlAttributes.AddAttribute("placeholder", metadata.Watermark));
}
}
public static class HtmlAttributesHelper
{
public static IDictionary<string, object> AddAttribute(this object htmlAttributes, string name, object value)
{
var dictionary = htmlAttributes == null ? new Dictionary<string, object>() : htmlAttributes.ToDictionary();
if (!String.IsNullOrWhiteSpace(name) && value != null && !String.IsNullOrWhiteSpace(value.ToString()))
dictionary.Add(name, value);
return dictionary;
}
public static IDictionary<string, object> ToDictionary(this object obj)
{
return TypeDescriptor.GetProperties(obj)
.Cast<PropertyDescriptor>()
.ToDictionary(property => property.Name, property => property.GetValue(obj));
}
}
Try something like this:
IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();
There's also a TryGetValues method on Headers you can use if you're not always guaranteed to have access to the header.
I was facing the same issue. I noticed that in my index i had both the "on device ready" and the "document.ready" function, so removing one of them fixed my problem :)
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
If Controls.Find is not found "textBox1" => error. You must add code.
If(tbx != null)
Edit:
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
If(tbx != null)
tbx.Text = "found!";
Try using {} instead of ():
${"file".$i} = file($filelist[$i]);
I simply just add e(fx)clipse in eclipse marketplace. Easy and simple
if you use more thread ExecutionServices SEQUENTIALLY and want to wait EACH EXECUTIONSERVICE to be finished. The best way is like below;
ExecutorService executer1 = Executors.newFixedThreadPool(THREAD_SIZE1);
for (<loop>) {
executer1.execute(new Runnable() {
@Override
public void run() {
...
}
});
}
executer1.shutdown();
try{
executer1.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
ExecutorService executer2 = Executors.newFixedThreadPool(THREAD_SIZE2);
for (true) {
executer2.execute(new Runnable() {
@Override
public void run() {
...
}
});
}
executer2.shutdown();
} catch (Exception e){
...
}
To sum it up, #pragma
tells the compiler to do stuff. Here are a couple of ways I use it:
#pragma
can be used to ignore compiler warnings. For example, to make GCC shut up about implicit function declarations, you can write:
#pragma GCC diagnostic ignored "-Wimplicit-function-declaration"
An older version of libportable
does this portably.
#pragma once
, when written at the top of a header file, will cause said header file to be included once. libportable
checks for pragma once support.
--bind_all
option is useful.
$ tensorboard --logdir runs --bind_all
The port will be automatically selected from 6006 incrementally.(6006, 6007, 6008... )
C99 offers some really cool stuff using anonymous arrays:
Removing pointless variables
{
int yes=1;
setsockopt(yourSocket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));
}
becomes
setsockopt(yourSocket, SOL_SOCKET, SO_REUSEADDR, (int[]){1}, sizeof(int));
Passing a Variable Amount of Arguments
void func(type* values) {
while(*values) {
x = *values++;
/* do whatever with x */
}
}
func((type[]){val1,val2,val3,val4,0});
Static linked lists
int main() {
struct llist { int a; struct llist* next;};
#define cons(x,y) (struct llist[]){{x,y}}
struct llist *list=cons(1, cons(2, cons(3, cons(4, NULL))));
struct llist *p = list;
while(p != 0) {
printf("%d\n", p->a);
p = p->next;
}
}
Any I'm sure many other cool techniques I haven't thought of.
RUBY
This code will reject the empty arrays and returns the proper array with values.
def find_sequence(val, num)
b = val.length
(0..b - 1).map {|n| val.uniq.combination(n).each.find_all {|value| value.reduce(:+) == num}}.reject(&:empty?)
end
val = [-10, 1, -1, 2, 0]
num = 2
Output will be [[2],[2,0],[-1,1,2],[-1,1,2,0]]
Jquery 3.0 has some breaking changes that remove certain methods due to conflicts. Your error is most likely due to one of these changes such as the removal of the .load() event.
Read more in the jQuery Core 3.0 Upgrade Guide
To fix this you either need to rewrite the code to be compatible with Jquery 3.0 or else you can use the JQuery Migrate plugin which restores the deprecated and/or removed APIs and behaviours.
If you make sure that this is the first event handler work, something like this might do the trick:
$('*').click(function(event) {
if (this === event.target) { // only fire this handler on the original element
alert('clicked');
}
});
Note that, if you have lots of elements in your page, this will be Really Very Slow, and it won't work for anything added dynamically.
I have a feeling that your ClientID
is not of a string type (zero-terminated char*
or std::string
) but some integral type (e.g. int
) so you need to convert number to the string first:
std::stringstream ss;
ss << ClientID;
query.append(ss.str());
But you can use operator+
as well (instead of append
):
query += ss.str();
You need to add the semicolon to the end of all php things like echo, functions, etc.
change <?php phpinfo() ?>
to <?php phpinfo(); ?>
If that does not work, use php's function ini_set to show errors: ini_set('display_errors', 1);
I had the same issue, testing a bunch of different examples, and tried all the possible solutions. What finally got it working for me was when I added a @Path("")
over the class line, I had left that out.
I wasted 1 day finding the issue , my system was not asking connection "allow" or "reject". i though it was due to some certiifcate issue . tried all methods mentioned above but none of them worked . in the end i found "Firewall was real culprit ". if firewall settings is ON , they will not allow charles to connect with your laptop via proxy IP . make them off and all things will work smoothly .Not sure if that was relevent answer but just want to share.
I encounter similar situation. I would like to have background of the last .item
to be yellow in the elements that look like...
<div class="container">
<div class="item">item 1</div>
<div class="item">item 2</div>
<div class="item">item 3</div>
...
<div class="item">item x</div>
<div class="other">I'm here for some reasons</div>
</div>
I use nth-last-child(2)
to achieve it.
.item:nth-last-child(2) {
background-color: yellow;
}
It strange to me because nth-last-child of item suppose to be the second of the last item but it works and I got the result as I expect. I found this helpful trick from CSS Trick
I think the simple method would be using
ob_start(); //Start output buffer
print_r($var);
$var = ob_get_contents(); //Grab output
ob_end_clean(); //Discard output buffer
and your array output will be recorded as a simple variable
You can pass in a pointer to a time_t
object that time
will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL
, it just ignores it and merely returns a new time_t
object that represents the current time.
For me, all I had to do is add maxReceivedMessageSize="2147483647"
to the client app.config. The server left untouched.
I want to slightly change the answer given by Wes, because version 0.16.2 requires as_index=False
. If you don't set it, you get an empty dataframe.
Aggregation functions will not return the groups that you are aggregating over if they are named columns, when
as_index=True
, the default. The grouped columns will be the indices of the returned object.Passing
as_index=False
will return the groups that you are aggregating over, if they are named columns.Aggregating functions are ones that reduce the dimension of the returned objects, for example:
mean
,sum
,size
,count
,std
,var
,sem
,describe
,first
,last
,nth
,min
,max
. This is what happens when you do for exampleDataFrame.sum()
and get back aSeries
.nth can act as a reducer or a filter, see here.
import pandas as pd
df1 = pd.DataFrame({"Name":["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"],
"City":["Seattle","Seattle","Portland","Seattle","Seattle","Portland"]})
print df1
#
# City Name
#0 Seattle Alice
#1 Seattle Bob
#2 Portland Mallory
#3 Seattle Mallory
#4 Seattle Bob
#5 Portland Mallory
#
g1 = df1.groupby(["Name", "City"], as_index=False).count()
print g1
#
# City Name
#Name City
#Alice Seattle 1 1
#Bob Seattle 2 2
#Mallory Portland 2 2
# Seattle 1 1
#
EDIT:
In version 0.17.1
and later you can use subset
in count
and reset_index
with parameter name
in size
:
print df1.groupby(["Name", "City"], as_index=False ).count()
#IndexError: list index out of range
print df1.groupby(["Name", "City"]).count()
#Empty DataFrame
#Columns: []
#Index: [(Alice, Seattle), (Bob, Seattle), (Mallory, Portland), (Mallory, Seattle)]
print df1.groupby(["Name", "City"])[['Name','City']].count()
# Name City
#Name City
#Alice Seattle 1 1
#Bob Seattle 2 2
#Mallory Portland 2 2
# Seattle 1 1
print df1.groupby(["Name", "City"]).size().reset_index(name='count')
# Name City count
#0 Alice Seattle 1
#1 Bob Seattle 2
#2 Mallory Portland 2
#3 Mallory Seattle 1
The difference between count
and size
is that size
counts NaN values while count
does not.
Use FromResult Method
public async Task<string> GetString()
{
System.Threading.Thread.Sleep(5000);
return await Task.FromResult("Hello");
}
If you specify Owner, you will get a Modal dialog over the specified WPF window.
To get WinForms compatible Win32 window create a class implements IWin32Window like this
public class OldWindow : System.Windows.Forms.IWin32Window
{
IntPtr _handle;
public OldWindow(IntPtr handle)
{
_handle = handle;
}
#region IWin32Window Members
IntPtr System.Windows.Forms.IWin32Window.Handle
{
get { return _handle; }
}
#endregion
}
And use an instance of this class at your WinForms
IntPtr mainWindowPtr = new WindowInteropHelper(this).Handle; // 'this' means WPF Window
folderBrowserDialog.ShowDialog(new OldWindow(mainWindowPtr));
We can easily do that in css3. We have to simply use @import statement. The following video easily describes the way how to do that. so go ahead and watch it out.
Add -storepass to keytool arguments.
keytool -storepasswd -storepass '' -keystore mykeystore.jks
But also notice that -list command does not always require a password. I could execute follow command in both cases: without password or with valid password
$JAVA_HOME/bin/keytool -list -keystore $JAVA_HOME/jre/lib/security/cacerts
Even though we have the .NPMRC can be in 3 locations, Please NOTE THAT - the file under the Per-User NPM config location take precedence over the Global & Built-in configurations.
To find out which file is getting updated, try setting the proxy using the following command npm config set https-proxy https://username:[email protected]:6050
After that open the .npmrc files to see which file get updated.
I am adding to Matt Brunell's answer.
string[] directories = myStringWithLotsOfFolders.Split(Path.DirectorySeparatorChar);
string previousEntry = string.Empty;
if (null != directories)
{
foreach (string direc in directories)
{
string newEntry = previousEntry + Path.DirectorySeparatorChar + direc;
if (!string.IsNullOrEmpty(newEntry))
{
if (!newEntry.Equals(Convert.ToString(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine(newEntry);
previousEntry = newEntry;
}
}
}
}
This should give you:
"\server"
"\server\folderName1"
"\server\folderName1\another name"
"\server\folderName1\another name\something"
"\server\folderName1\another name\something\another folder\"
(or sort your resulting collection by the string.Length of each value.
I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.
Here's the code:
/**
* @author Lonkly
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param ? - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> ?) {
Field field = null;
int resId = 0;
try {
field = ?.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
I recommend taking a look at Ryan Tomayko's How I Explained REST to My Wife
Excerpt from the waybackmaschine link:
How about an example. You’re a teacher and want to manage students:
If the systems are web-based, then there’s probably a URL for each of the nouns involved here: student, teacher, class, book, room, etc
. ... If there were a machine readable representation for each URL, then it would be trivial to latch new tools onto the system because all of that information would be consumable in a standard way. ... you could build a country-wide system that was able to talk to each of the individual school systems to collect testing scores.
Each of the systems would get information from each other using a simple HTTP GET. If one system needs to add something to another system, it would use an HTTP POST. If a system wants to update something in another system, it uses an HTTP PUT. The only thing left to figure out is what the data should look like.
Okay, I've compiled the Time and Space complexities of basic operations on graphs.
The image below should be self-explanatory.
Notice how Adjacency Matrix is preferable when we expect the graph to be dense, and how Adjacency List is preferable when we expect the graph to be sparse.
I've made some assumptions. Ask me if a complexity (Time or Space) needs clarification. (For example, For a sparse graph, I've taken En to be a small constant, as I've assumed that addition of a new vertex will add only a few edges, because we expect the graph to remain sparse even after adding that vertex.)
Please tell me if there are any mistakes.
It should work as well
Eval("item") == null?"0": Eval("item");
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
For myself, I just encode it in the url and use $_GET on the destination page. Here's a line as an example.
$ch = curl_init();
$this->json->p->method = "whatever";
curl_setopt($ch, CURLOPT_URL, "http://" . $_SERVER['SERVER_NAME'] . $this->json->path . '?json=' . urlencode(json_encode($this->json->p)));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
EDIT: Adding the destination snippet... (EDIT 2 added more above at OPs request)
<?php
if(!isset($_GET['json']))
die("FAILURE");
$json = json_decode($_GET['json']);
$method = $json->method;
...
?>
Do you need a type attribute at all? If you're using HTML5, no. Otherwise, yes. HTML 4.01 and XHTML 1.0 specifies the type
attribute as required while HTML5 has it as optional, defaulting to text/javascript
. HTML5 is now widely implemented, so if you use the HTML5 doctype, <script>...</script>
is valid and a good choice.
As to what should go in the type attribute, the MIME type application/javascript
registered in 2006 is intended to replace text/javascript
and is supported by current versions of all the major browsers (including Internet Explorer 9). A quote from the relevant RFC:
This document thus defines text/javascript and text/ecmascript but marks them as "obsolete". Use of experimental and unregistered media types, as listed in part above, is discouraged. The media types,
* application/javascript * application/ecmascript
which are also defined in this document, are intended for common use and should be used instead.
However, IE up to and including version 8 doesn't execute script inside a <script>
element with a type
attribute of either application/javascript
or application/ecmascript
, so if you need to support old IE, you're stuck with text/javascript
.
New, detailed answer and explanation to an old, frequently asked question...
Short answer: If you don't add elementFormDefault="qualified"
to xsd:schema
, then the default unqualified
value means that locally declared elements are in no namespace.
There's a lot of confusion regarding what elementFormDefault
does, but this can be quickly clarified with a short example...
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:target="http://www.levijackson.net/web340/ns"
targetNamespace="http://www.levijackson.net/web340/ns">
<element name="assignments">
<complexType>
<sequence>
<element name="assignment" type="target:assignmentInfo"
minOccurs="1" maxOccurs="unbounded"/>
</sequence>
</complexType>
</element>
<complexType name="assignmentInfo">
<sequence>
<element name="name" type="string"/>
</sequence>
<attribute name="id" type="string" use="required"/>
</complexType>
</schema>
Key points:
assignment
element is locally defined.elementFormDefault
is unqualified
.elementFormDefault="qualified"
so that assignment
is in the target namespace as one would
expect.form
attribute on xs:element
declarations for which elementFormDefault
establishes default values.This XML looks like it should be valid according to the above XSD:
<assignments xmlns="http://www.levijackson.net/web340/ns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.levijackson.net/web340/ns try.xsd">
<assignment id="a1">
<name>John</name>
</assignment>
</assignments>
Notice:
assignments
places assignments
and all of its descendents in the default namespace (http://www.levijackson.net/web340/ns
).Despite looking valid, the above XML yields the following confusing validation error:
[Error] try.xml:4:23: cvc-complex-type.2.4.a: Invalid content was found starting with element 'assignment'. One of '{assignment}' is expected.
Notes:
assignment
element but it actually found an assignment
element. (WTF){
and }
around assignment
means that validation was expecting assignment
in no namespace here. Unfortunately, when it says that it found an assignment
element, it doesn't mention that it found it in a default namespace which differs from no namespace.elementFormDefault="qualified"
to the xsd:schema
element of the XSD. This means valid XML must place elements in the target namespace when locally declared in the XSD; otherwise, valid XML must place locally declared elements in no namespace.assignment
be in no namespace. This can be achieved,
for example, by adding xmlns=""
to the assignment
element.Credits: Thanks to Michael Kay for helpful feedback on this answer.
if you install the maven with the brew
you can type the command("mvn -v") in Terminal
see Maven home detail
mvn -v
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T03:39:06+08:00)
Maven home: /usr/local/Cellar/maven/3.5.0/libexec
Java version: 1.8.0_121, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "mac os x", version: "10.11.5", arch: "x86_64", family: "mac"
Use sqlalchemy's text function to remove the interpretation of special characters:
Note the use of the function text("your_insert_statement")
below. What it does is communicate to sqlalchemy that all of the questionmarks and percent signs in the passed in string should be considered as literals.
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re
engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
% ("your_username", "your_password", "your_hostname_mysql_server:3306",
"your_database"),
pool_size=3, pool_recycle=3600)
conn = engine.connect()
myfile = open('access2.log', 'r')
lines = myfile.readlines()
penguins = []
for line in lines:
elements = re.split('\s+', line)
print "item: " + elements[0]
linedate = datetime.fromtimestamp(float(elements[0]))
mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")
penguins.append(text(
"insert into your_table (foobar) values('%%%????')"))
for penguin in penguins:
print penguin
conn.execute(penguin)
conn.close()
I archive this using LinearLayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:height="166dp"
android:text="Tile1"
android:gravity="center"
android:background="#6f19e5"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="Tile2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:height="126dp"
android:gravity="center"
android:layout_weight=".50"
android:background="#f1d600"/>
<TextView
android:text="Tile3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:height="126dp"
android:gravity="center"
android:layout_weight=".50"
android:background="#e75548"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:text="Tile4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:height="126dp"
android:gravity="center"
android:layout_weight=".50"
android:background="#29d217"/>
<TextView
android:text="Tile5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:height="126dp"
android:gravity="center"
android:layout_weight=".50"
android:background="#e519cb"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:height="176dp"
android:text="Tile6"
android:gravity="center"
android:background="#09eadd"/>
</LinearLayout>
</LinearLayout>
I know this is too late for sure, but, this could help someone as well.
In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).
Make sure that you can copy from the command prompt,
It might be related to corruption in Angular Packages or incompatibility of packages.
Please follow the below steps to solve the issue.
Update
ASP.NET Boilerplate suggests here to use yarn because npm has some problems. It is slow and can not consistently resolve dependencies, yarn solves those problems and it is compatible to npm as well.
If you are using virtualenv, it is not as trivial to get the driver using the installer. What you can do then: install it as described by Devon. Then copy over cx_Oracle.pyd and the cx_Oracle-XXX.egg-info folder from Python\Lib\site-packages into the Lib\site-packages from your virtual env. Of course, also here, architecture and version are important.
What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);
my @array = ();
should work just fine -- it allocates a new array called @array
, and then assigns it the empty list, ()
. Note that this is identical to simply saying my @array;
, since the initial value of a new array is the empty list anyway.
Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings;
in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)
I would use NSPredicate
:
func isValidEmail(_ email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
for versions of Swift earlier than 3.0:
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailPred.evaluate(with: email)
}
for versions of Swift earlier than 1.2:
func isValidEmail(email: String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) {
return emailPred.evaluateWithObject(email)
}
return false
}
Yes. You can use Process.Start
to launch an executable, including a console application.
If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.
You can Add this :
...
dlg.dialog({ autoOpen:false,
modal: true,
width: 400,
open: function(){ // There is new line
$("#txtStartDate").focus();
}
});
...
128M == 134217728
, the number you are seeing.
The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.
Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.
Worked for Windows Server 2008 and Chrome v64:
The best way to do this is by a simple check and assess. I usually do something like this:
#ifndef _DEPRECATION_DISABLE /* One time only */
#define _DEPRECATION_DISABLE /* Disable deprecation true */
#if (_MSC_VER >= 1400) /* Check version */
#pragma warning(disable: 4996) /* Disable deprecation */
#endif /* #if defined(NMEA_WIN) && (_MSC_VER >= 1400) */
#endif /* #ifndef _DEPRECATION_DISABLE */
All that is really required is the following:
#pragma warning(disable: 4996)
Hasn't failed me yet; Hope this helps
Counting to 2^128 - ambitious.
Lets imagine that we can count 2^32 IDs per second per machine - not that ambitious, since it's not even 4.3 billion per second. Lets dedicate 2^32 machines to that task. Furthermore, lets get 2^32 civilisations to each dedicate the same resources to the task.
So far, we can count 2^96 IDs per second, meaning we will be counting for 2^32 seconds (a little over 136 years).
Now, all we need is to get 4,294,967,296 civilisations to each dedicate 4,294,967,296 machines, each machine capable of counting 4,294,967,296 IDs per second, purely to this task for the next 136 years or so - I suggest we get started on this essential task right now ;-)
Have you tried to define a custom background in xml? decreasing the Spinner background width which is doing your arrow look like that.
Define a layer-list with a rectangle background and your custom arrow icon:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/color_white" />
<corners android:radius="2.5dp" />
</shape>
</item>
<item android:right="64dp">
<bitmap android:gravity="right|center_vertical"
android:src="@drawable/custom_spinner_icon">
</bitmap>
</item>
</layer-list>
Based on what I see here, you have used lowercase fieldnames in your $data
array, and uppercase fieldnames in your database table.
@Pascal's comment on the OP's question is right. By simply adding the image, it removes the black borders and the app will use the full height.
You will need to make adjustments to any CGRects by determining that the device is using the bigger display. I.e. If you need something aligned to the bottom of the screen.
I am sure there is a built in method, but I haven't seen anything and a lot is still under NDA so the method we use in our apps is quite simply a global function. Add the following to your .pch file and then its a simple if( is4InchRetina() ) { ... }
call to make adjustments to your CGRects etc.
static BOOL is4InchRetina()
{
if (![UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 548 || [UIApplication sharedApplication].statusBarHidden && (int)[[UIScreen mainScreen] applicationFrame].size.height == 568)
return YES;
return NO;
}
First of all, The solution for remote server:
If you are using cpanel you may have zip extension installed but not activate. You need to active it. For this case you need to go to cpanel > inside software section > click on PHP version. Then find zip and check it. Now save.
You should see like the image.
Refresh page. The error should disappear.
Note: If you dont found, contact server provider. They will install for you.
add this to your my.cnf
innodb_buffer_pool_size=1G
restart your mysql to make it effect
try to run the code below
- (void)viewDidLoad {
[super viewDidLoad];
UIWindow *w = [[UIApplication sharedApplication] keyWindow];
UIView *v = [w.subviews objectAtIndex:0];
NSLog(@"%@", NSStringFromCGRect(v.frame));
NSLog(@"%@", NSStringFromCGRect(v.bounds));
}
the output of this code is:
case device orientation is Portrait
{{0, 0}, {768, 1024}}
{{0, 0}, {768, 1024}}
case device orientation is Landscape
{{0, 0}, {768, 1024}}
{{0, 0}, {1024, 768}}
obviously, you can see the difference between frame and bounds
If you want to avoid hardcoding your keystore & password in build.gradle, you can use a properties file as explained here: HANDLING SIGNING CONFIGS WITH GRADLE
Basically:
1) create a myproject.properties file at /home/[username]/.signing with such contents:
keystore=[path to]\release.keystore
keystore.password=*********
keyAlias=***********
keyPassword=********
2) create a gradle.properties file (perhaps at the root of your project directory) with the contents:
MyProject.properties=/home/[username]/.signing/myproject.properties
3) refer to it in your build.gradle like this:
if(project.hasProperty("MyProject.properties")
&& new File(project.property("MyProject.properties")).exists()) {
Properties props = new Properties()
props.load(new FileInputStream(file(project.property("MyProject.properties"))))
signingConfigs {
release {
storeFile file(props['keystore'])
storePassword props['keystore.password']
keyAlias props['keyAlias']
keyPassword props['keyPassword']
}
}
}
What's happening is that since the the TextView is filling the whole width of the inner LinearLayout it is already in the horizontal center of the layout. When you use android:layout_gravity
it places the widget, as a whole, in the gravity specified. Instead of placing the whole widget center what you're really trying to do is place the content in the center which can be accomplished with android:gravity="center_horizontal"
and the android:layout_gravity
attribute can be removed.
You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:
var config=document.getElementsByName('configselect').value;
because you have declared only the name
attribute in your <select>
tag. So you should get this element by name.
After correcting this, it will run without any JavaScript error
In fact, xargs
can run commands in parallel for you. There is a special -P max_procs
command-line option for that. See man xargs
.
If using MySQL Workbench, simply look in the Session tab in the Information pane located in the sidebar.
Two ways. Either create a button and style it so it looks like a link with css, or create a link and use onclick="this.closest('form').submit();return false;"
.
The simplest way especially if you don't have a context, if you're using RxAndroid you can do:
AndroidSchedulers.mainThread().scheduleDirect {
runCodeHere()
}
$.browser
has been removed from JQuery 1.9. You can to use Modernizr project instead
http://jquery.com/upgrade-guide/1.9/#jquery-browser-removed
UPDATE TO SUPPORT IE 10 AND IE 11 (TRIDENT version)
To complete the @daniel.moura answer, here is a version which support IE 11 and +
var matched, browser;
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie)[\s?]([\w.]+)/.exec( ua ) ||
/(trident)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
//IE 11+ fix (Trident)
matched.browser = matched.browser == 'trident' ? 'msie' : matched.browser;
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
// log removed - adds an extra dependency
//log(jQuery.browser)
To delete null and also empty entries Try this
foreach (var column in drEntitity.Columns.Cast<DataColumn>().ToArray())
{
if (drEntitity.AsEnumerable().All(dr => dr.IsNull(column) | string.IsNullOrEmpty( dr[column].ToString())))
drEntitity.Columns.Remove(column);
}
In theory you can use PhpStorm to visualise your classes using UML. The generation is not really great but you can effectively refactor stuff and again, at least preview parents, implementations, constants, attributes, methods and their visibility in a nice way.
Situation
I want to visualise a communication between already existing components to a colleague.
Process using PHPStorm
https://blog.jetbrains.com/phpstorm/2017/09/uml-diagrams-in-phpstorm-2017-2/
Advantages
Disadvantages
Result
Anyway, after some painful hour of work I was only able to generate unrelated boxes and had to use additional program to link relations. Really bad. But I believe once they make it work properly it will be a great feature because as the code changes, the diagrams would be automatically updated!
For now, don't use PhpStorm for UML diagrams.
macOS Sierra 10.12.6. Wasn't able to install anything through pip (python installed through homebrew). All the answers above didn't work.
Eventually, upgrade from python 3.5 to 3.6 worked.
brew update
brew doctor #(in case you see such suggestion by brew)
then follow any additional suggestions by brew, i.e. overwrite link to python.
You can access the Axes instance (ax
) with plt.gca()
. In this case, you can use
plt.gca().legend()
You can do this either by using the label=
keyword in each of your plt.plot()
calls or by assigning your labels as a tuple or list within legend
, as in this working example:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()
However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax
with
ax = plt.gca()
and then calling ax
instead of plt.gca()
.
iOS Status bar has only 2 options (black and white). You can try this in AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleLightContent];
}
To delete rows from a table, you need to provide selection criteria that identify the rows to the delete()
method. The mechanism works the same as the selection arguments to the query()
method. It divides the selection specification into a selection clause(where clause) and selection arguments.
SQLiteDatabase db = this.getWritableDatabase();
// Define 'where' part of query.
String selection = Contract.COLUMN_COMPANY_ID + " =? and "
+ Contract.CLOUMN_TYPE +" =? ";
// Specify arguments in placeholder order.
String[] selectionArgs = { cid,mode };
// Issue SQL statement.
int deletedRows = db.delete(Contract.TABLE_NAME,
selection, selectionArgs);
return deletedRows;// no.of rows deleted.
The return value for the delete()
method indicates the number of rows that were deleted from the database.
When hosted in docker containers (linux version for me), you might get a 'Connection Refused' message. In that case you can use IP address 0.0.0.0 which means "all IP addresses on this machine" instead of the localhost loopback to fix the port forwarding.
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls("http://0.0.0.0:5000/")
.Build();
host.Run();
}
}
In my case it was related to vs-code running on my Linux machine. I ignored a warning which popped up about file watcher bla bla. The solution is on the vs-code docs page for linux https://code.visualstudio.com/docs/setup/linux#_visual-studio-code-is-unable-to-watch-for-file-changes-in-this-large-workspace-error-enospc
The solution is almost same (if not same) as the accepted answers, just has more explanation for anyone who gets here after running into the issues from vs-code.
You can do this from info.plist:
1) "View controller-based status bar appearance" set to "NO"
2) "Status bar style" set to "UIStatusBarStyleLightContent"
done
Unfortunately the opacity
element makes the whole element (including any text) semi-transparent. The best way to make the border semi-transparent is with the rgba color format. For example, this would give a red border with 50% opacity:
div {
border: 1px solid rgba(255, 0, 0, .5);
-webkit-background-clip: padding-box; /* for Safari */
background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}
The problem with this approach is that some browsers do not understand the rgba
format and will not display any border at all if this is the entire declaration. The solution is to provide two border declarations. The first with a fake opacity, and the second with the actual. If a browser is capable, it will use the second, if not, it will use the first.
div {
border: 1px solid rgb(127, 0, 0);
border: 1px solid rgba(255, 0, 0, .5);
-webkit-background-clip: padding-box; /* for Safari */
background-clip: padding-box; /* for IE9+, Firefox 4+, Opera, Chrome */
}
The first border declaration will be the equivalent color to a 50% opaque red border over a white background (although any graphics under the border will not bleed through).
UPDATE: I've added "background-clip: padding-box;" to this answer (per SooDesuNe's suggestion in the comments) to ensure the border remains transparent even if a solid background color is applied.
If Template is not set (i.e. ==null), this error will be raised, too.
More comments:
If you know the parameter value by the time you add parameters, you can also use AddWithValue
The EXEC is not required. You can reference the @template parameter in the SELECT directly.
your issue will be resolved by properly defining cascading depedencies or by saving the referenced entities before saving the entity that references. Defining cascading is really tricky to get right because of all the subtle variations in how they are used.
Here is how you can define cascades:
@Entity
public class Userrole implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long userroleid;
private Timestamp createddate;
private Timestamp deleteddate;
private String isactive;
//bi-directional many-to-one association to Role
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="ROLEID")
private Role role;
//bi-directional many-to-one association to User
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="USERID")
private User user;
}
In this scenario, every time you save, update, delete, etc Userrole, the assocaited Role and User will also be saved, updated...
Again, if your use case demands that you do not modify User or Role when updating Userrole, then simply save User or Role before modifying Userrole
Additionally, bidirectional relationships have a one-way ownership. In this case, User owns Bloodgroup. Therefore, cascades will only proceed from User -> Bloodgroup. Again, you need to save User into the database (attach it or make it non-transient) in order to associate it with Bloodgroup.
One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.
>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0
Therefore, I use the following to test if a numpy array has elements:
>>> def elements(array):
... return array.ndim and array.size
>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24
No. Well, not really. There are a couple of selectors that can get you somewhat close, but probably won't work in your example and don't have the best browser compatibility.
:only-child
The :only-child
is one of the few true counting selectors in the sense that it's only applied when there is one child of the element's parent. Using your idealized example, it acts like children(1)
probably would.
:nth-child
The :nth-child
selector might actually get you where you want to go depending on what you're really looking to do. If you want to style all elements if there are 8 children, you're out of luck. If, however, you want to apply styles to the 8th and later elements, try this:
p:nth-child( n + 8 ){
/* add styles to make it pretty */
}
Unfortunately, these probably aren't the solutions you're looking for. In the end, you'll probably need to use some Javascript wizardry to apply the styles based on the count - even if you were to use one of these, you'd need to have a hard look at browser compatibility before going with a pure CSS solution.
W3 CSS3 Spec on pseudo-classes
EDIT I read your question a little differently - there are a couple other ways to style the parent, not the children. Let me throw a few other selectors your way:
:empty
and :not
This styles elements that have no children. Not that useful on its own, but when paired with the :not
selector, you can style only the elements that have children:
div:not(:empty) {
/* We know it has stuff in it! */
}
You can't count how many children are available with pure CSS here, but it is another interesting selector that lets you do cool things.
In VB.NET
<%=Html.ActionLink("Contact Us", "ContactUs", "Home", Nothing, New With {.class = "link"})%>
This will assign css class "link" to the Contact Us.
This will generate following HTML :
<a class="link" href="www.domain.com/Home/ContactUs">Contact Us</a>
You can do using OnClientClick of button.
OnClientClick="return confirm('confirm delete')"
If you're into C# and VB.Net and don't mind open source then you could use SharpDevelop. It does a pretty good job!
You need to use a group by clause.
SELECT site_id, MAX(ts) as TIME, count(*) group by site_id
Use the time package to work with time information in Go.
Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.
Play example:
package main
import (
"fmt"
"time"
)
func inTimeSpan(start, end, check time.Time) bool {
return check.After(start) && check.Before(end)
}
func main() {
start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")
in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")
if inTimeSpan(start, end, in) {
fmt.Println(in, "is between", start, "and", end, ".")
}
if !inTimeSpan(start, end, out) {
fmt.Println(out, "is not between", start, "and", end, ".")
}
}
The simple way to do this is doing a div within a div
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 1_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 2_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
<div class="server-action-menu" id="server_1">Server 3_x000D_
</div>_x000D_
</div>
_x000D_
@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -
plot(rnorm(30), xlab = expression('4'^th*'moment'))
May I suggest Node ORM?
https://github.com/dresende/node-orm2
There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.
MongoDB is available since version 2.1.x (released in July 2013)
UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
There is no way to do this. Your options are to use a JavaScript or a CSS block.
Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block. But then the code will not be standard-compliant.
this is happening because your code is not bale to connect the database. Make sure you have mysql driver and username, password correct.
int i = 0;
while(rs.next()) {
i++;
}
Your original logic for creating the matrix is indeed correct, and it even works in Swift 2. The problem is that in the print loop, you have the row and column variables reversed. If you change it to:
for row in 0...2 {
for column in 0...2 {
print("column: \(column) row: \(row) value:\(array[column][row])")
}
}
you will get the correct results. Hope this helps!
If you need to do this for a large number of textboxes (in Silverlight or WPF), then you can use the technique used in the blog post: http://dnchannel.blogspot.com/2010/01/silverlight-3-auto-select-text-in.html. It uses Attached Properties and Routed Events.
for me, this solution didn't worked on a command exec with find, don't really know why, so my solution is
find . -type f -path "./a/*" -prune -o -path "./b/*" -prune -o -exec gzip -f -v {} \;
Explanation: same as sampson-chen one with the additions of
-prune - ignore the proceding path of ...
-o - Then if no match print the results, (prune the directories and print the remaining results)
18:12 $ mkdir a b c d e
18:13 $ touch a/1 b/2 c/3 d/4 e/5 e/a e/b
18:13 $ find . -type f -path "./a/*" -prune -o -path "./b/*" -prune -o -exec gzip -f -v {} \;
gzip: . is a directory -- ignored
gzip: ./a is a directory -- ignored
gzip: ./b is a directory -- ignored
gzip: ./c is a directory -- ignored
./c/3: 0.0% -- replaced with ./c/3.gz
gzip: ./d is a directory -- ignored
./d/4: 0.0% -- replaced with ./d/4.gz
gzip: ./e is a directory -- ignored
./e/5: 0.0% -- replaced with ./e/5.gz
./e/a: 0.0% -- replaced with ./e/a.gz
./e/b: 0.0% -- replaced with ./e/b.gz
A solution that works no matter if you are developing on a local server or live is to add "//" in front of your link. This will effectivly remove the URL of the site you are currently on.
Example:
<a href="www.google.com">Google.com</a>
This will in output http://localhost/mySite/currentPage/www.google.com
What you should do instead is this:
<a href="//www.google.com">Google.com</a>
This will output www.google.com
1- Select LinearLayout findViewById
LinearLayout llayout =(LinearLayout) findViewById(R.id.llayoutId);
2- Set color from R.color.colorId
llayout.setBackgroundColor(getResources().getColor(R.color.colorId));
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
void displayBinary(int n)
{
char bistr[1000];
itoa(n,bistr,2); //2 means binary u can convert n upto base 36
printf("%s",bistr);
}
int main()
{
int n;
cin>>n;
displayBinary(n);
getch();
return 0;
}
System.Diagnostics.Process.Start("PathToExe.exe");
Here is the full code with no errors
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
#map-canvas
{
height: 400px;
width: 500px;
}
</style>
</script>
<script type="text/javascript">
function initialize() {
var myLatLng = new google.maps.LatLng( 17.3850, 78.4867 ),
myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
marker = new google.maps.Marker( {icon: {
url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(20, 32),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 32)
}, position: myLatLng, map: map} );
marker.setMap( map );
moveBus( map, marker );
}
function moveBus( map, marker ) {
setTimeout(() => {
marker.setPosition( new google.maps.LatLng( 12.3850, 77.4867 ) );
map.panTo( new google.maps.LatLng( 17.3850, 78.4867 ) );
}, 1000)
};
</script>
</head>
<body onload="initialize()">
<script type="text/javascript">
//moveBus();
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=AIzaSyB-W_sLy7VzaQNdckkY4V5r980wDR9ldP4"></script>
<div id="map-canvas" style="height: 500px; width: 500px;"></div>
</body>
</html>
Worth noting, that depending on your purpose (mine was the autofill results of a searchbar) you may want the height to be changeable, and for the scrollbar to only exist if the height exceeds that.
If you want that, replace height: x;
with max-height: x;
, and overflow:scroll
with overflow:auto
.
Additionally, you can use overflow-x
and overflow-y
if you want, and obviously the same thing works horizontally with width : x;
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Confirm!'
}).then(function(){
alert("The confirm button was clicked");
}).catch(function(reason){
alert("The alert was dismissed by the user: "+reason);
});
You forgot to add self
as a parameter to the function worker()
in the class KeyStatisticCollection
.
for empty all input tags such as input,select,textatea etc. run this code
$('#message').val('').change();
As no one mentioned Arm MAP, I'd add it as personally I have successfully used Map to profile a C++ scientific program.
Arm MAP is the profiler for parallel, multithreaded or single threaded C, C++, Fortran and F90 codes. It provides in-depth analysis and bottleneck pinpointing to the source line. Unlike most profilers, it's designed to be able to profile pthreads, OpenMP or MPI for parallel and threaded code.
MAP is commercial software.
If you have
char[] c
then you can do
char* d = &c[0]
and access element c[1] by doing *(d+1)
, etc.
This could be the easiest in my opinion:
SELECT * FROM `table` WHERE `timestamp` like concat(CURDATE(),'%');
Code for MainActivity.java file.
public class MainActivity extends Activity {
ListView listview;
Button Addbutton;
EditText GetValue;
String[] ListElements = new String[] {
"Android",
"PHP"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView1);
Addbutton = (Button) findViewById(R.id.button1);
GetValue = (EditText) findViewById(R.id.editText1);
final List < String > ListElementsArrayList = new ArrayList < String >
(Arrays.asList(ListElements));
final ArrayAdapter < String > adapter = new ArrayAdapter < String >
(MainActivity.this, android.R.layout.simple_list_item_1,
ListElementsArrayList);
listview.setAdapter(adapter);
Addbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ListElementsArrayList.add(GetValue.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
}
Code for activity_main.xml layout file.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.listviewaddelementsdynamically_android_examples
.com.MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:text="ADD Values to listview" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:ems="10"
android:hint="Add elements listView" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
ScreenShot
You can use Timer
Timer timer = new Timer();
timer.schedule( new TimerTask() {
public void run() {
// do your work
}
}, 0, 60*1000);
When the times comes
timer.cancel();
To shut it down.
See the git-pull man page:
git pull [options] [<repository> [<refspec>...]]
and in the examples section:
Merge into the current branch the remote branch next:
$ git pull origin next
So I imagine you want to do something like:
git pull origin dev
To set it up so that it does this by default while you're on the dev branch:
git branch --set-upstream-to dev origin/dev
In my case, the MissingMethodException was for a method that was in the same file!
However, I had just added a NuGet package that uses .Net Standard2 to my 4.7.1-targeting project, which caused a version conflict for System.Net.Http (4.7.1: version 4.0.0.0, the NuGet package using .NET Standard 2 wants 4.2.0.0). This seem to be known issues that should be better in 4.7.2 (see note 2).
I had used a binding redirect like this in all other my projects, because there were exceptions as soon as it tried to load the 4.2.0.0 which I didn't have:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
Except in this one project, where it seems it tries to load System.Net.Http only while calling a local function that uses a System.Net.Http.HttpResponseMessage as it's parameter or return type (parameter during debugging, return type when I run the tests without the debugger, also a bit strange). And instead of showing a message that it could not load the 4.2.0.0 version of System.Net.Http, it returns this exception.
How about trying this:
using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
//do your code here
}
}
}
Actually, RFC 2965, the document that defines how cookies work, specifies that there should be no maximum length of a cookie's key or value size, and encourages implementations to support arbitrarily large cookies. Each browser's implementation maximum will necessarily be different, so consult individual browser documentation.
See section 5.3, "Implementation Limits", in the RFC.
I've been testing alternatives to C# Web browser component for few days now and here is my list:
1. Using newer IE versions 8,9:
Web Browser component is IE7 not IE8? How to change this?
Pros:
Cons:
This doesn't require much work and you can get some HTML5 and CSS3 support although IE9 lacks some of best CSS3 and HTML5 features. But I'm sure you could get IE10 running same way. The problem would be that target system would have to have IE10 installed, and since is still in preview on Windows 7 I would suggest against it.
OpenWebKitSharp is a .net wrapper for the webkit engine based on the WebKit.NET 0.5 project. WebKit is a layout engine used by Chrome/Safari
Pros:
Cons:
OpenWebKit is quite nice although many features are not yet implemented, I experienced few issues using it with visual studio which throws null object reference here and then in design mode, there are some js problems. Everyone using it will almost immediately notice js alert does nothing. Events like mouseup,mousedown... etc. doesn't work, js drag and drop is buggy and so on..
I also had some difficulties installing it since it requires specific version of VC redistributable installed, so after exception I looked at event log, found version of VC and installed it.
3. GeckoFX
Pros:
Cons:
GeckoFX is a cross platform Webrowser control for embedding into WinForms Applications. This can be used with .NET on Windows and with mono on Linux. Gecko is a layout engine used by Firefox.
I bumped into few information that GeckoFX is not actively developed which is not true, of course it's always one or two versions behind of Firefox but that is normal, I was really impressed by activity and the control itself. It does everything I needed, but I needed some time to get it running, here's a little tutorial to get it running:
If your really must use Chrome, take a look at this product called Awesomium, it's free for non-commercial projects, but license is few thousand dollars for commercial.
For me i had already created a folder with name excel in wwroot D:\working directory\OnlineExam\wwwroot\excel And i was trying to copy a file with name excel which was already existing as a folder name. the path which was required was D:\working directory\OnlineExam\wwwroot\excel\finance.csv so according i changed the code as below
string copyPath = Path.Combine(_webHostEnvironment.WebRootPath, "excel\\finance");
questionExcelUpload.Upload.CopyTo(new FileStream(copyPath, FileMode.Create));
Basically check if a folder or a file with same name as your path exist already.
I created a possibly faster implementation by using 0-1 range for RGBS and V and 0-6 range for Hue (avoiding the division), and grouping the cases into two categories:
#include <math.h>
#include <float.h>
void fromRGBtoHSV(float rgb[], float hsv[])
{
// for(int i=0; i<3; ++i)
// rgb[i] = max(0.0f, min(1.0f, rgb[i]));
hsv[0] = 0.0f;
hsv[2] = max(rgb[0], max(rgb[1], rgb[2]));
const float delta = hsv[2] - min(rgb[0], min(rgb[1], rgb[2]));
if (delta < FLT_MIN)
hsv[1] = 0.0f;
else
{
hsv[1] = delta / hsv[2];
if (rgb[0] >= hsv[2])
{
hsv[0] = (rgb[1] - rgb[2]) / delta;
if (hsv[0] < 0.0f)
hsv[0] += 6.0f;
}
else if (rgb[1] >= hsv[2])
hsv[0] = 2.0f + (rgb[2] - rgb[0]) / delta;
else
hsv[0] = 4.0f + (rgb[0] - rgb[1]) / delta;
}
}
void fromHSVtoRGB(const float hsv[], float rgb[])
{
if(hsv[1] < FLT_MIN)
rgb[0] = rgb[1] = rgb[2] = hsv[2];
else
{
const float h = hsv[0];
const int i = (int)h;
const float f = h - i;
const float p = hsv[2] * (1.0f - hsv[1]);
if (i & 1) {
const float q = hsv[2] * (1.0f - (hsv[1] * f));
switch(i) {
case 1:
rgb[0] = q;
rgb[1] = hsv[2];
rgb[2] = p;
break;
case 3:
rgb[0] = p;
rgb[1] = q;
rgb[2] = hsv[2];
break;
default:
rgb[0] = hsv[2];
rgb[1] = p;
rgb[2] = q;
break;
}
}
else
{
const float t = hsv[2] * (1.0f - (hsv[1] * (1.0f - f)));
switch(i) {
case 0:
rgb[0] = hsv[2];
rgb[1] = t;
rgb[2] = p;
break;
case 2:
rgb[0] = p;
rgb[1] = hsv[2];
rgb[2] = t;
break;
default:
rgb[0] = t;
rgb[1] = p;
rgb[2] = hsv[2];
break;
}
}
}
}
For 0-255 range just * 255.0f + 0.5f and assign it to an unsigned char (or divide by 255.0 to get the opposite).
If you do not want to use runOnUiThread
API, you can in fact implement AsynTask
for the operations that takes some seconds to complete. But in that case, also after processing your work in doinBackground()
, you need to return the finished view in onPostExecute()
. The Android implementation allows only main UI thread to interact with views.
I use self-written Printer class, but dir() is also good for outputting the instance fields/values.
class Printer:
def __init__ (self, PrintableClass):
for name in dir(PrintableClass):
value = getattr(PrintableClass,name)
if '_' not in str(name).join(str(value)):
print ' .%s: %r' % (name, value)
The sample of usage:
Printer(MyClass)
You have to use initiailzers:
class DerivedClass : public BaseClass
{
public:
DerivedClass()
: BaseClass(<insert arguments here>)
{
}
};
This is also how you construct members of your class that don't have constructors (or that you want to initialize). Any members not mentioned will be default initialized. For example:
class DerivedClass : public BaseClass
{
public:
DerivedClass()
: BaseClass(<insert arguments here>)
, nc(<insert arguments here>)
//di will be default initialized.
{
}
private:
NeedsConstructor nc;
CanBeDefaultInit di;
};
The order the members are specified in is irrelevant (though the constructors must come first), but the order that they will be constructed in is in declaration order. So nc
will always be constructed before di
.
Try implementing the interface as anonymous.
public class MyClass extends MySuperClass implements MyInterface{
MyInterface myInterface = new MyInterface(){
/* Overrided method from interface */
@override
public void method1(){
}
};
/* Overrided method from superclass*/
@override
public void method1(){
}
}
finally I found... it will work nice when table displays only 3 rows... if rows are more change should be accordingly...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text =[NSString stringWithFormat:@"Hello roe no. %d",[indexPath row]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * theCell = (UITableViewCell *)[tableView
cellForRowAtIndexPath:indexPath];
CGPoint tableViewCenter = [tableView contentOffset];
tableViewCenter.y += myTable.frame.size.height/2;
[tableView setContentOffset:CGPointMake(0,theCell.center.y-65) animated:YES];
[tableView reloadData];
}