IT baffles me sometimes to why a software company would develop its own scripting language to interface with their software, rather than building a strong API that can interface with your scripting language of choice. My vote goes to TransCAD's scripting language.
For me the following seemed to work.
git pull --tags
here is what i did:
window.addEventListener('orientationchange', doOnOrientationChange);
function doOnOrientationChange()
{
if (screen.height > screen.width) {
console.log('portrait');
} else {
console.log('landscape');
}
}
There is a Firebug-like tool already built into Chrome. Just right click anywhere on a page and choose "Inspect element" from the menu. Chrome has a graphical tool for debugging (like in Firebug), so you can debug JavaScript. It also does CSS inspection well and can even change CSS rendering on the fly.
For more information, see https://developers.google.com/chrome-developer-tools/
Both Date
and moment
will parse the input string in the local time zone of the browser by default. However Date
is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD
, using hyphens, or if it is YYYY-MM-DD HH:mm:ss
, it will interpret it as local time. Unlike Date
, moment
will always be consistent about how it parses.
The correct way to parse an input moment as UTC in the format you provided would be like this:
moment.utc('07-18-2013', 'MM-DD-YYYY')
Refer to this documentation.
If you want to then format it differently for output, you would do this:
moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')
You do not need to call toString
explicitly.
Note that it is very important to provide the input format. Without it, a date like 01-04-2013
might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.
Yes. You know that you can put any Object
into the Object
parameter of most JOptionPane.showXXX methods
, and often that Object
happens to be a JPanel
.
In your situation, perhaps you could use a JPanel
that has several JTextFields
in it:
import javax.swing.*;
public class JOptionPaneMultiInput {
public static void main(String[] args) {
JTextField xField = new JTextField(5);
JTextField yField = new JTextField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("x:"));
myPanel.add(xField);
myPanel.add(Box.createHorizontalStrut(15)); // a spacer
myPanel.add(new JLabel("y:"));
myPanel.add(yField);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("x value: " + xField.getText());
System.out.println("y value: " + yField.getText());
}
}
}
@robert-hurst has a cleaner approach.
However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.
// select canvas elements
var sourceCanvas = document.getElementById("some-unique-id");
var destCanvas = document.getElementsByClassName("some-class-selector")[0];
//copy canvas by DataUrl
var sourceImageData = sourceCanvas.toDataURL("image/png");
var destCanvasContext = destCanvas.getContext('2d');
var destinationImage = new Image;
destinationImage.onload = function(){
destCanvasContext.drawImage(destinationImage,0,0);
};
destinationImage.src = sourceImageData;
As of Go 1.4, the go generate
tool has been introduced together with the stringer
command that makes your enum easily debuggable and printable.
The new pathlib
library simplifies this to one line:
from pathlib import Path
result = list(Path(PATH).glob('**/*.txt'))
You can also use the generator version:
from pathlib import Path
for file in Path(PATH).glob('**/*.txt'):
pass
This returns Path
objects, which you can use for pretty much anything, or get the file name as a string by file.name
.
In C, you can use the built in qsort
command:
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
if ( int_a == int_b ) return 0;
else if ( int_a < int_b ) return -1;
else return 1;
}
qsort( a, 6, sizeof(int), compare )
see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/
To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.
As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort
I have had to do this several times and have researched many different solutions.
The solution I find in most elegant and easy to accomplish can be implemented as such.
the interface will contain signatures of any members you wish to call.
public interface IExampleProxy
{
string HelloWorld( string name );
}
Its important to keep this project clean and lite. It is a project that both AppDomain
's can reference and will allow us to not reference the Assembly
we wish to load in seprate domain from our client assembly.
AppDomain
.This project as with the client proj will reference the proxy proj and you will implement the interface.
public interface Example : MarshalByRefObject, IExampleProxy
{
public string HelloWorld( string name )
{
return $"Hello '{ name }'";
}
}
AppDomain
.So, now we create a new AppDomain
. Can specify the base location for assembly references. Probing will check for dependent assemblies in GAC and in current directory and the AppDomain
base loc.
// set up domain and create
AppDomainSetup domaininfo = new AppDomainSetup
{
ApplicationBase = System.Environment.CurrentDirectory
};
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain exampleDomain = AppDomain.CreateDomain("Example", adevidence, domaininfo);
// assembly ant data names
var assemblyName = "<AssemblyName>, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null|<keyIfSigned>";
var exampleTypeName = "Example";
// Optional - get a reflection only assembly type reference
var @type = Assembly.ReflectionOnlyLoad( assemblyName ).GetType( exampleTypeName );
// create a instance of the `Example` and assign to proxy type variable
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( assemblyName, exampleTypeName );
// Optional - if you got a type ref
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( @type.Assembly.Name, @type.Name );
// call any members you wish
var stringFromOtherAd = proxy.HelloWorld( "Tommy" );
// unload the `AppDomain`
AppDomain.Unload( exampleDomain );
if you need to, there are a ton of different ways to load an assembly. You can use a different way with this solution. If you have the assembly qualified name then I like to use the CreateInstanceAndUnwrap
since it loads the assembly bytes and then instantiates your type for you and returns an object
that you can simple cast to your proxy type or if you not that into strongly-typed code you could use the dynamic language runtime and assign the returned object to a dynamic
typed variable then just call members on that directly.
This allows to load an assembly that your client proj doesnt have reference to in a seperate AppDomain
and call members on it from client.
The key is to either make sure you code either derives MarshalByRefObject
or is serializable.
`MarshalByRefObject will allow you to configure the lifetime of the domain its in. Example, say you want the domain to destroy if the proxy hasnt been called in 20 minutes.
Another simple option that updates on a click of the checkbox.
HTML:
<input type="checkbox" id="checkbox/>
<input disabled type="submit" id="item"/>
jQuery:
$('#checkbox').click(function() {
if (this.checked) {
$('#item').prop('disabled', false); // If checked enable item
} else {
$('#item').prop('disabled', true); // If checked disable item
}
});
In action: link
Try
SELECT li.clientid, group_concat(li.views ORDER BY li.views) AS views,
group_concat(li.percentage ORDER BY li.percentage)
FROM table_views li
GROUP BY client_id
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat
PasswordDialog dlg = new PasswordDialog(this);
if(dlg.showDialog() == DialogResult.OK)
{
//blabla, anything your self
}
public class PasswordDialog extends Dialog
{
int dialogResult;
Handler mHandler ;
public PasswordDialog(Activity context, String mailName, boolean retry)
{
super(context);
setOwnerActivity(context);
onCreate();
TextView promptLbl = (TextView) findViewById(R.id.promptLbl);
promptLbl.setText("Input password/n" + mailName);
}
public int getDialogResult()
{
return dialogResult;
}
public void setDialogResult(int dialogResult)
{
this.dialogResult = dialogResult;
}
/** Called when the activity is first created. */
public void onCreate() {
setContentView(R.layout.password_dialog);
findViewById(R.id.cancelBtn).setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View paramView)
{
endDialog(DialogResult.CANCEL);
}
});
findViewById(R.id.okBtn).setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View paramView)
{
endDialog(DialogResult.OK);
}
});
}
public void endDialog(int result)
{
dismiss();
setDialogResult(result);
Message m = mHandler.obtainMessage();
mHandler.sendMessage(m);
}
public int showDialog()
{
mHandler = new Handler() {
@Override
public void handleMessage(Message mesg) {
// process incoming messages here
//super.handleMessage(msg);
throw new RuntimeException();
}
};
super.show();
try {
Looper.getMainLooper().loop();
}
catch(RuntimeException e2)
{
}
return dialogResult;
}
}
Regarding objects, especially in lazy-load scenario, one should consider garbage collector is running in idle CPU cycles, so presuming you're going into trouble when a lot of objects are loading small time penalty will solve the memory freeing.
Use time_nanosleep to enable GC to collect memory. Setting variable to null is desirable.
Tested on production server, originally the job consumed 50MB and then was halted. After nanosleep was used 14MB was constant memory consumption.
One should say this depends on GC behaviour which may change from PHP version to version. But it works on PHP 5.3 fine.
eg. this sample (code taken form VirtueMart2 google feed)
for($n=0; $n<count($ids); $n++)
{
//unset($product); //usefull for arrays
$product = null
if( $n % 50 == 0 )
{
// let GC do the memory job
//echo "<mem>" . memory_get_usage() . "</mem>";//$ids[$n];
time_nanosleep(0, 10000000);
}
$product = $productModel->getProductSingle((int)$ids[$n],true, true, true);
...
You can use case in update and SWAP as many as you want
update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns
FOR SPECIFIC NUM:
SELECT COUNT(1) FROM YOUR_TABLE WHERE NUM = 1
FOR ALL NUM:
SELECT NUM, COUNT(1) FROM YOUR_TABLE GROUP BY NUM
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
bmleite has the correct answer about including the module.
If that is correct in your situation, you should also ensure that you are not redefining the modules in multiple files.
Remember:
angular.module('ModuleName', []) // creates a module.
angular.module('ModuleName') // gets you a pre-existing module.
So if you are extending a existing module, remember not to overwrite when trying to fetch it.
The vue documentation provides a lot of information on this on how you can deploy to different host providers.
npm run build
You can find this from the package json file. scripts section. It provides scripts for testing and development and building for production.
You can use services such as netlify which will bundle your project by linking up your github repo of the project from their site. It also provides information on how to deploy on other sites such as heroku.
You can find more details on this here
Here is C# version in Xamarin.iOS
var alert = new UIAlertView("Title - Hey!", "Message - Hello iOS!", null, "Ok");
alert.Show();
<!--Customize button -->
<LinearGradientBrush x:Key="Buttongradient" StartPoint="0.500023,0.999996" EndPoint="0.500023,4.37507e-006">
<GradientStop Color="#5e5e5e" Offset="1" />
<GradientStop Color="#0b0b0b" Offset="0" />
</LinearGradientBrush>
<Style x:Key="hhh" TargetType="{x:Type Button}">
<Setter Property="Background" Value="{DynamicResource Buttongradient}"/>
<Setter Property="Foreground" Value="White" />
<Setter Property="FontSize" Value="15" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="4" Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="0.5">
<Border.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="2"></DropShadowEffect>
</Border.Effect>
<Grid>
<Path Width="9" Height="16.5" Stretch="Fill" Fill="#000" HorizontalAlignment="Left" Margin="16.5,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z " Opacity="0.2">
</Path>
<Path x:Name="PathIcon" Width="8" Height="15" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z ">
<Path.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="5"></DropShadowEffect>
</Path.Effect>
</Path>
<Line HorizontalAlignment="Left" Margin="40,0,0,0" Name="line4" Stroke="Black" VerticalAlignment="Top" Width="2" Y1="0" Y2="640" Opacity="0.5" />
<ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#E59400" />
<Setter Property="Foreground" Value="White" />
<Setter TargetName="PathIcon" Property="Fill" Value="Black" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="OrangeRed" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
An IEnumerator
is a thing that can enumerate: it has the Current
property and the MoveNext
and Reset
methods (which in .NET code you probably won't call explicitly, though you could).
An IEnumerable
is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator
.
Which do you use? The only reason to use IEnumerator
is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator
. But you'd still need to return that IEnumerator
in an IEnumerable
class.
For a look at what an enumerator (implementing IEnumerator<T>
) looks like, see any Enumerator<T>
class, such as the ones contained in List<T>
, Queue<T>,
or Stack<T>
. For a look at a class implementing IEnumerable
, see any standard collection class.
I had problems with this and this is the story (sad but true) :
If your table name is all lower case like : accounts
you can use: select * from AcCounTs
and it will work fine
If your table name is all lower case like : accounts
The following will fail:
select * from "AcCounTs"
If your table name is mixed case like : Accounts
The following will fail:
select * from accounts
If your table name is mixed case like : Accounts
The following will work OK:
select * from "Accounts"
I dont like remembering useless stuff like this but you have to ;)
The code above works perfectly with one minor flaw; the resulting file is not saved with a .csv extension. – Tensigh 2 days ago
I added the following to code and it saved my file as a csv. Thanks for this bit of code.It all worked as expected.
ActiveWorkbook.SaveAs Filename:=SaveToDirectory & ThisWorkbook.Name & "-" & WS.Name & ".csv", FileFormat:=xlCSV
public static byte[] my_int_to_bb_le(int myInteger){
return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}
public static int my_bb_to_int_le(byte [] byteBarray){
return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
public static byte[] my_int_to_bb_be(int myInteger){
return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}
public static int my_bb_to_int_be(byte [] byteBarray){
return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}
Open the file in Notepad. Click 'Save As...'. In the 'Encoding:' combo box you will see the current file format.
Here is a work around. You can use filter instead of find; but filter returns an array of matching objects. find
only returns the first match inside an array. So, why not use filter as following;
data.filter(function (x) {
return x.Id === e
})[0];
A Java list is a collection of objects ... the elements of a list. The size of the list is the number of elements in that list. If you want that size to be fixed, that means that you cannot either add or remove elements, because adding or removing elements would violate your "fixed size" constraint.
The simplest way to implement a "fixed sized" list (if that is really what you want!) is to put the elements into an array and then Arrays.asList(array)
to create the list wrapper. The wrapper will allow you to do operations like get
and set
, but the add
and remove
operations will throw exceptions.
And if you want to create a fixed-sized wrapper for an existing list, then you could use the Apache commons FixedSizeList
class. But note that this wrapper can't stop something else changing the size of the original list, and if that happens the wrapped list will presumably reflect those changes.
On the other hand, if you really want a list type with a fixed limit (or limits) on its size, then you'll need to create your own List class to implement this. For example, you could create a wrapper class that implements the relevant checks in the various add
/ addAll
and remove
/ removeAll
/ retainAll
operations. (And in the iterator remove
methods if they are supported.)
So why doesn't the Java Collections framework implement these? Here's why I think so:
Collections.sort
.Here's something that might be interesting for developers hacking (minified or obfuscated) JavaScript more frequently.
You can build your own CLI JavaScript beautifier in under 5 mins and have it handy on the command-line. You'll need Mozilla Rhino, JavaScript file of some of the JS beautifiers available online, small hack and a script file to wrap it all up.
I wrote an article explaining the procedure: Command-line JavaScript beautifier implemented in JavaScript.
Example with no parameters:
delegate void NewEventHandler();
public event NewEventHandler OnEventHappens;
And from another class, you can subscribe to
otherClass.OnEventHappens += ExecuteThisFunctionWhenEventHappens;
And declare that function with no parameters.
In Swift 1.2:
@IBAction func openLink {
let pth = "http://www.google.com"
if let url = NSURL(string: pth){
UIApplication.sharedApplication().openURL(url)
}
I think you may want to introduce some helper functions to build
your button as well as a Stateful widget along with some property to key off of.
isButtonDisabled
)onPressed
value to either null
or some function onPressed: () {}
isButtonDisabled
as part of this conditional and return either null
or some function.setState(() => isButtonDisabled = true)
to flip the conditional variable.build()
method again with the new state and the button will be rendered with a null
press handler and be disabled.Here's is some more context using the Flutter counter project.
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool _isButtonDisabled;
@override
void initState() {
_isButtonDisabled = false;
}
void _incrementCounter() {
setState(() {
_isButtonDisabled = true;
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("The App"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
_buildCounterButton(),
],
),
),
);
}
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _isButtonDisabled ? null : _incrementCounter,
);
}
}
In this example I am using an inline ternary to conditionally set the Text
and onPressed
, but it may be more appropriate for you to extract this into a function (you can use this same method to change the text of the button as well):
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _counterButtonPress(),
);
}
Function _counterButtonPress() {
if (_isButtonDisabled) {
return null;
} else {
return () {
// do anything else you may want to here
_incrementCounter();
};
}
}
Yes if you are using latest java which is version 8. Java8 make it possible to define anonymous functions which was impossible in previous versions.
Lets take example from java docs to get know how we can declare anonymous functions, classes
The following example, HelloWorldAnonymousClasses, uses anonymous classes in the initialization statements of the local variables frenchGreeting and spanishGreeting, but uses a local class for the initialization of the variable englishGreeting:
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
class EnglishGreeting implements HelloWorld {
String name = "world";
public void greet() {
greetSomeone("world");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld englishGreeting = new EnglishGreeting();
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
HelloWorld spanishGreeting = new HelloWorld() {
String name = "mundo";
public void greet() {
greetSomeone("mundo");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hola, " + name);
}
};
englishGreeting.greet();
frenchGreeting.greetSomeone("Fred");
spanishGreeting.greet();
}
public static void main(String... args) {
HelloWorldAnonymousClasses myApp =
new HelloWorldAnonymousClasses();
myApp.sayHello();
}
}
Syntax of Anonymous Classes
Consider the instantiation of the frenchGreeting object:
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
The anonymous class expression consists of the following:
new
operatorThe name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
Definitely this gives good solution,
ResultSet rs = stmt.execute("SQL QUERY");
// With the above statement you will not have a null ResultSet 'rs'.
// In case, if any exception occurs then next line of code won't execute.
// So, no problem if I won't check rs as null.
if (rs.next()) {
do {
// Logic to retrieve the data from the resultset.
// eg: rs.getString("abc");
} while(rs.next());
} else {
// No data
}
OAuth is a protocol with which a 3-party app can access your data stored in another website without your account and password. For a more official definition, refer to the Wiki or specification.
Here is a use case demo:
I login to LinkedIn and want to connect some friends who are in my Gmail contacts. LinkedIn supports this. It will request a secure resource (my gmail contact list) from gmail. So I click this button:
A web page pops up, and it shows the Gmail login page, when I enter my account and password:
Gmail then shows a consent page where I click "Accept":
Now LinkedIn can access my contacts in Gmail:
Below is a flowchart of the example above:
Step 1: LinkedIn requests a token from Gmail's Authorization Server.
Step 2: The Gmail authorization server authenticates the resource owner and shows the user the consent page. (the user needs to login to Gmail if they are not already logged-in)
Step 3: User grants the request for LinkedIn to access the Gmail data.
Step 4: the Gmail authorization server responds back with an access token.
Step 5: LinkedIn calls the Gmail API with this access token.
Step 6: The Gmail resource server returns your contacts if the access token is valid. (The token will be verified by the Gmail resource server)
You can get more from details about OAuth here.
I also had the same issue while playing around Zend Framework 2 and composer. I'm using PHP 5.4 (installed via macports) and my solution was to install openssl for PHP 5.4 via macports as well.
sudo port install php54-openssl
If you have your navbar inside a component and you declared your style active in that stylesheet, it won't work. In my case this was the problem.
my item of my navbar using angular material was:
<div class="nav-item">
<a routerLink="/test" routerLinkActive="active">
<mat-icon>monetization_on</mat-icon>My link
</a>
<mat-divider class="nav-divider" [vertical]="true"></mat-divider>
so I put the style active in my style.scss in the root
a.active {
color: white !important;
mat-icon {
color: white !important;
}
}
I hope it helps you if the other solutions didn't.
Interestingly, the HttpWebResponse.GetResponseStream()
that you get from the WebException.Response
is not the same as the response stream that you would have received from server. In our environment, we're losing actual server responses when a 400 HTTP status code is returned back to the client using the HttpWebRequest/HttpWebResponse
objects. From what we've seen, the response stream associated with the WebException's HttpWebResponse
is generated at the client and does not include any of the response body from the server. Very frustrating, as we want to message back to the client the reason for the bad request.
These documents describe data dictionary views:
all_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_4473.htm#REFRN26286
user_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_2105.htm#i1592091
dba_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_4155.htm#i1627762
You can run queries on these views to count what you need.
To add something more to @Anurag Thakre's answer:
Use this query which will give you the actual no of counts respect to the owners
SELECT COUNT(*),tablespace_name FROM USER_TABLES group by tablespace_name;
Or by table owners:
SELECT COUNT(*), owner FROM ALL_TABLES group by owner;
Tablespace itself does not identify an unique object owner. Multiple users can create objects in the same tablespace and a single user can create objects in various tablespaces. It is a common practice to separate tables and indexes into different tablespaces.
I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local
, which is executed about last in init phase.
This command with --user 0 do the job:
adb uninstall --user 0 <package_name>
For Ubuntu xampp,
Go to /opt/lampp/etc/extra/
and open httpd-xampp.conf file and add below lines to get remote access,
Order allow,deny
Require all granted
Allow from all
in /opt/lampp/phpmyadmin section.
And restart lampp using, /opt/lampp/lampp restart
You can use ICU4J, Just need to add POM entry and code is below for any Number, Country and Language.
POM Entry
<dependency>
<groupId>com.ibm.icu</groupId>
<artifactId>icu4j</artifactId>
<version>64.2</version>
</dependency>
Code is
public class TranslateNumberToWord {
/**
* Translate
*
* @param ctryCd
* @param lang
* @param reqStr
* @param fractionUnitName
* @return
*/
public static String translate(String ctryCd, String lang, String reqStr, String fractionUnitName) {
StringBuffer result = new StringBuffer();
Locale locale = new Locale(lang, ctryCd);
Currency crncy = Currency.getInstance(locale);
String inputArr[] = StringUtils.split(new BigDecimal(reqStr).abs().toPlainString(), ".");
RuleBasedNumberFormat rule = new RuleBasedNumberFormat(locale, RuleBasedNumberFormat.SPELLOUT);
int i = 0;
for (String input : inputArr) {
CurrencyAmount crncyAmt = new CurrencyAmount(new BigDecimal(input), crncy);
if (i++ == 0) {
result.append(rule.format(crncyAmt)).append(" " + crncy.getDisplayName() + " and ");
} else {
result.append(rule.format(crncyAmt)).append(" " + fractionUnitName + " ");
}
}
return result.toString();
}
public static void main(String[] args) {
String ctryCd = "US";
String lang = "en";
String input = "95.17";
String result = translate(ctryCd, lang, input, "Cents");
System.out.println("Input: " + input + " result: " + result);
}}
Tested with quite a big number and output would be
Input: 95.17 result: ninety-five US Dollar and seventeen Cents
Input: 999999999999999999.99 result: nine hundred ninety-nine quadrillion nine hundred ninety-nine trillion nine hundred ninety-nine billion nine hundred ninety-nine million nine hundred ninety-nine thousand nine hundred ninety-nine US Dollar and ninety-nine Cents
The issue is finding an alternative to MS Access that includes a visual, drag and drop development environment with a "reasonable" database where the whole kit and caboodle can be deployed free of charge.
My first suggestion would be to look at this very complete list of MS Access alternatives (many of which are free), followed by a gander at this list of open source database development tools on osalt.com.
My second suggestion would be to check out WaveMaker, which is sort of an open source PowerBuilder for the cloud (disclaimer: I work there so should not be considered to be an unbiased source of information ;-)
WaveMaker combines a drag and drop IDE with an open source Java back end. It is licensed under the Apache license and boasts a 15,000-strong developer community.
Reload the current page:
F5
or
CTRL + R
Reload the current page, ignoring cached content (i.e. JavaScript files, images, etc.):
SHIFT + F5
or
CTRL + F5
or
CTRL + SHIFT + R
The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.
You have to get name and value from craft in your template :
<script type="text/javascript">
window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>
and pass them in your request
data: window.csrfTokenName+"="+window.csrfTokenValue
Current version:
Settings
(Preferences
on Mac) | Build, Execution, Deployment
| Compiler
|
Build process heap size.
Older versions:
Settings
(Preferences
on Mac) | Compiler
| Java Compiler
| Maximum heap size.
Compiler runs in a separate JVM by default so IDEA heap settings that you set in idea.vmoptions
have no effect on the compiler.
You can try overflow
css property.
Even i ran into the same issue with mysql and liquibase. So this is what the problem is: The table from which you want to reference a column of other table is different either in case of datatype or in terms of size of the datatype.
Error appears in below scenario:
Scenario 1:
Table A has column id, type=bigint
Table B column referenced_id type varchar(this column gets the value from the id column of Table A.)
Liquibase changeset for table B:
<changeset id="XXXXXXXXXXX-1" author="xyz">
<column name="referenced_id" **type="varchar"**>
</column>
</changeset>
<changeSet id="XXXXXXXXXXX-2" author="xyz">
<addForeignKeyConstraint constraintName="FK_table_A"
referencedTableName="A" **baseColumnNames="referenced_id**"
referencedColumnNames="id" baseTableName="B" />
</changeSet>
Table A changeSet:
<changeSet id="YYYYYYYYYY" author="xyz">
<column **name="id"** **type="bigint"** autoIncrement="${autoIncrement}">
<constraints primaryKey="true" nullable="false"/>
</column>
</changeSet>
Solution:
correct the type of table B to bigint because the referenced table has type bigint.
Scenrario 2:
The type might be correct but the size might not.
e.g. :
Table B : referenced column type="varchar 50"
Table A : base column type ="varchar 255"
Solution change the size of referenced column to that of base table's column size.
AFAIK, the browser (at least Firefox) requests every resource as soon as it parses it. If it encounters an img tag it will request that image as soon as the img tag has been parsed. And that can be even before it has received the totality of the HTML document... that is it could still be downloading the HTML document when that happens.
For Firefox, there are browser queues that apply, depending on how they are set in about:config. For example it will not attempt to download more then 8 files at once from the same server... the additional requests will be queued. I think there are per-domain limits, per proxy limits, and other stuff, which are documented on the Mozilla website and can be set in about:config. I read somewhere that IE has no such limits.
The jQuery ready event is fired as soon as the main HTML document has been downloaded and it's DOM parsed. Then the load event is fired once all linked resources (CSS, images, etc.) have been downloaded and parsed as well. It is made clear in the jQuery documentation.
If you want to control the order in which all that is loaded, I believe the most reliable way to do it is through JavaScript.
Code in Kotlin:
var updateSongTime = object : Runnable {
override fun run() {
val getCurrent = mediaPlayer?.currentPosition
startTimeText?.setText(String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long),
TimeUnit.MILLISECONDS.toSeconds(getCurrent?.toLong()) -
TimeUnit.MINUTES.toSeconds(
TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong()))))
seekBar?.setProgress(getCurrent?.toInt() as Int)
Handler().postDelayed(this, 1000)
}
}
For changing media player audio file every second
If user drags the seek bar then following code snippet can be use
Statified.seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
if(b && Statified.mediaPlayer != null){
Statified.mediaPlayer?.seekTo(i)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
})
I’d suggest you find yourself a 3rd party tool for this such as ApexSQL Search (there are probably others out there too but I use this one because it’s free).
If you really want to go the SQL way you can try using stored procedure created by Sorna Kumar Muthuraj – copied code is below. Just execute this stored procedure for all tables in your schema (easy with dynamics SQL)
CREATE PROCEDURE SearchTables
@Tablenames VARCHAR(500)
,@SearchStr NVARCHAR(60)
,@GenerateSQLOnly Bit = 0
AS
/*
Parameters and usage
@Tablenames -- Provide a single table name or multiple table name with comma seperated.
If left blank , it will check for all the tables in the database
@SearchStr -- Provide the search string. Use the '%' to coin the search.
EX : X%--- will give data staring with X
%X--- will give data ending with X
%X%--- will give data containig X
@GenerateSQLOnly -- Provide 1 if you only want to generate the SQL statements without seraching the database.
By default it is 0 and it will search.
Samples :
1. To search data in a table
EXEC SearchTables @Tablenames = 'T1'
,@SearchStr = '%TEST%'
The above sample searches in table T1 with string containing TEST.
2. To search in a multiple table
EXEC SearchTables @Tablenames = 'T2'
,@SearchStr = '%TEST%'
The above sample searches in tables T1 & T2 with string containing TEST.
3. To search in a all table
EXEC SearchTables @Tablenames = '%'
,@SearchStr = '%TEST%'
The above sample searches in all table with string containing TEST.
4. Generate the SQL for the Select statements
EXEC SearchTables @Tablenames = 'T1'
,@SearchStr = '%TEST%'
,@GenerateSQLOnly = 1
*/
SET NOCOUNT ON
DECLARE @CheckTableNames Table
(
Tablename sysname
)
DECLARE @SQLTbl TABLE
(
Tablename SYSNAME
,WHEREClause VARCHAR(MAX)
,SQLStatement VARCHAR(MAX)
,Execstatus BIT
)
DECLARE @sql VARCHAR(MAX)
DECLARE @tmpTblname sysname
IF LTRIM(RTRIM(@Tablenames)) IN ('' ,'%')
BEGIN
INSERT INTO @CheckTableNames
SELECT Name
FROM sys.tables
END
ELSE
BEGIN
SELECT @sql = 'SELECT ''' + REPLACE(@Tablenames,',',''' UNION SELECT ''') + ''''
INSERT INTO @CheckTableNames
EXEC(@sql)
END
INSERT INTO @SQLTbl
( Tablename,WHEREClause)
SELECT SCh.name + '.' + ST.NAME,
(
SELECT '[' + SC.name + ']' + ' LIKE ''' + @SearchStr + ''' OR ' + CHAR(10)
FROM SYS.columns SC
JOIN SYS.types STy
ON STy.system_type_id = SC.system_type_id
AND STy.user_type_id =SC.user_type_id
WHERE STY.name in ('varchar','char','nvarchar','nchar')
AND SC.object_id = ST.object_id
ORDER BY SC.name
FOR XML PATH('')
)
FROM SYS.tables ST
JOIN @CheckTableNames chktbls
ON chktbls.Tablename = ST.name
JOIN SYS.schemas SCh
ON ST.schema_id = SCh.schema_id
WHERE ST.name <> 'SearchTMP'
GROUP BY ST.object_id, SCh.name + '.' + ST.NAME ;
UPDATE @SQLTbl
SET SQLStatement = 'SELECT * INTO SearchTMP FROM ' + Tablename + ' WHERE ' + substring(WHEREClause,1,len(WHEREClause)-5)
DELETE FROM @SQLTbl
WHERE WHEREClause IS NULL
WHILE EXISTS (SELECT 1 FROM @SQLTbl WHERE ISNULL(Execstatus ,0) = 0)
BEGIN
SELECT TOP 1 @tmpTblname = Tablename , @sql = SQLStatement
FROM @SQLTbl
WHERE ISNULL(Execstatus ,0) = 0
IF @GenerateSQLOnly = 0
BEGIN
IF OBJECT_ID('SearchTMP','U') IS NOT NULL
DROP TABLE SearchTMP
EXEC (@SQL)
IF EXISTS(SELECT 1 FROM SearchTMP)
BEGIN
SELECT Tablename=@tmpTblname,* FROM SearchTMP
END
END
ELSE
BEGIN
PRINT REPLICATE('-',100)
PRINT @tmpTblname
PRINT REPLICATE('-',100)
PRINT replace(@sql,'INTO SearchTMP','')
END
UPDATE @SQLTbl
SET Execstatus = 1
WHERE Tablename = @tmpTblname
END
SET NOCOUNT OFF
go
I would change your binding to be:
<button type="button" value="click me" onclick="check_me" />
I would then change your check_me()
function declaration to be:
function check_me() {
//event.preventDefault();
var hello = document.myForm.username.value;
var err = '';
if(hello == '' || hello == null) {
err = 'User name required';
}
if(err != '') {
alert(err);
$('username').focus();
event.preventDefault();
} else {
return true; }
}
Using the same charset (as suggested here) in both the database and the HTML has not worked for me... So remembering that the code is generated as HTML, I chose to use the "
(HTML code) or the "
(ISO Latin-1 code) in my database text where quotes were used. This solved the problem while providing me a quotation mark. It is odd to note that prior to this solution, only some of the quotation marks and apostrophes did not display correctly while others did, however, the special code did work in all instances.
Generally, it means the program you are trying to run does not have a "main" method. If you are going to execute a Java program, the class being executed must have a main
method:
For example, in the file Foo.java
public class Foo {
public static void main(final String args[]) {
System.out.println("hello");
}
}
This program should compile and run no problem - if main
was called something else, or was not static, it would generate the error you experienced.
Every executable program, regardless of language, needs an entry point, to tell the interpreter, operating system or machine where to start execution. In Java's case, this is the static method main
, which is passed the parameter args[]
containing the command line arguments. This method is equivalent to int main(int argc, char** argv)
in C language.
In my template driven form (Angular 6) I have the following workaround:
<div class='col-sm-2 form-group'>
<label for='amount'>Amount</label>
<input type='number'
id='amount'
name='amount'
required
[ngModel] = 1
[pattern] = "'^[1-9][0-9]*$'"
class='form-control'
#amountInput='ngModel'/>
<span class='text-danger' *ngIf="amountInput.touched && amountInput.invalid">
<p *ngIf="amountInput.errors?.required">This field is <b>required</b>!</p>
<p *ngIf="amountInput.errors?.pattern">This minimum amount is <b>1</b>!</p>
</span>
</div>
Alot of the above examples make use of directives and custom classes which do scale better in more complex forms, but if your looking for a simple numeric min, utilize pattern
as a directive and impose a regex restriction on positive numbers only.
# cases
$x = null
$x = ''
$x = ' '
# test
if ($x -and $x.trim()) {'not empty'} else {'empty'}
or
if ([string]::IsNullOrWhiteSpace($x)) {'empty'} else {'not empty'}
Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use timeit
's default_timer()
:
>>> import timeit
>>> tic=timeit.default_timer()
>>> # Do Stuff
>>> toc=timeit.default_timer()
>>> toc - tic #elapsed time in seconds
This will return the elapsed wall clock (real) time, not CPU time. And as described in the timeit
documentation chooses the most precise available real-world timer depending on the platform.
ALso, beginning with Python 3.3 this same functionality is available with the time.perf_counter
performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.
For more precise/complex performance calculations, timeit
includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.
USE THIS ONLY IF YOU HAVE LIMITED NUMBER OF ITEMS IN YOUR RECYCLER VIEW.
I tried using boolean value in model and keep the checkbox status, but it did not help in my case.
What worked for me is this.setIsRecyclable(false);
public class ComponentViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
....
this.setIsRecyclable(false);
}
More explanation on this can be found here https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#isRecyclable()
NOTE: This is a workaround. To use it properly you can refer the document which states "Calls to setIsRecyclable() should always be paired (one call to setIsRecyclabe(false) should always be matched with a later call to setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally reference-counted." I don't know how to do this in code, if someone can provide more code on this.
There are three possibilities:
1) If you are referring old DLL then it cant be used. So you have refer new DLL
2) If you are using it in different namespace and trying to use the other namespace's dll then it wont refer this method.
3) You may need to rebuild the project
I think third option might be the cause for you. Please post more information in order to understand exact problem of yours.
About clang iOS cross-compiler
I've found that the problem was at miphoneos-version-min=5.0
. I've changed into miphoneos-version-min=8.0
. Now it works.
I just want suggest to use create a simple test.c file and compile it by the command write in the log.
Do this:
date('Y-m-d', strtotime('dd/mm/yyyy'));
But make sure 'dd/mm/yyyy' is the actual date.
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
Here you go:
DECLARE
BEGIN
dbms_output.enable(NULL); -- Disables the limit of DBMS
-- Your print here !
END;
I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -
Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")
The Range("A1") in Sheet1 of Book1 now contains "A".
Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.:
break;
case R.id.:
break;
default:
break;
}
}
What had caused this error on my side was the following line
include_once dirname(__FILE__) . './Config.php';
I managed to realize it was the culprit when i added the lines:
//error_reporting(E_ALL | E_DEPRECATED | E_STRICT);
//ini_set('display_errors', 1);
to all my php files.
To solve the path issue
i canged the offending line to:
include_once dirname(__FILE__) . '/Config.php';
use datetime library http://docs.python.org/library/datetime.html look up 9.1.7. especiall strptime() strftime() Behavior¶ examples http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Not sure whether you have already gotten your owner solution. I have been using the following powshell command to achieve it:
powershell.exe -noprofile -command "Invoke-WebRequest -Uri http://your_url"
As an complement to Stefan Steiger answer: (as it doesn't look nice as a comment)
Extending String prototype:
String.prototype.b64encode = function() {
return btoa(unescape(encodeURIComponent(this)));
};
String.prototype.b64decode = function() {
return decodeURIComponent(escape(atob(this)));
};
Usage:
var str = "äöüÄÖÜçéèñ";
var encoded = str.b64encode();
console.log( encoded.b64decode() );
NOTE:
As stated in the comments, using unescape
is not recommended as it may be removed in the future:
Warning: Although unescape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states: … All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification.
Note: Do not use unescape to decode URIs, use decodeURI or decodeURIComponent instead.
To download file on flask call. File name is Examples.pdf When I am hitting 127.0.0.1:5000/download it should get download.
Example:
from flask import Flask
from flask import send_file
app = Flask(__name__)
@app.route('/download')
def downloadFile ():
#For windows you need to use drive name [ex: F:/Example.pdf]
path = "/Examples.pdf"
return send_file(path, as_attachment=True)
if __name__ == '__main__':
app.run(port=5000,debug=True)
Even after toggling it did not work. I closed and restarted the browser after adding the postman plugin, logged into the site to generate cookies afresh and then it worked for me.
Fine then. You can use CSS word wrap property. Something like this :
td.test /* Give whatever class name you want */
{
width:11em; /* Give whatever width you want */
word-wrap:break-word;
}
Rather than use multiple classes or class inheritance, perhaps a single Toy class that knows what "kind" it is:
class Toy:
num = 0
def __init__(self, name, kind, *args):
self.name = name
self.kind = kind
self.data = args
self.num = Toy.num
Toy.num += 1
def __repr__(self):
return ' '.join([self.name,self.kind,str(self.num)])
def playWith(self):
print self
def getNewToy(name, kind):
return Toy(name, kind)
t1 = Toy('Suzie', 'doll')
t2 = getNewToy('Jack', 'robot')
print t1
t2.playWith()
Running it:
$ python toy.py
Suzie doll 0
Jack robot 1
As you can see, getNewToy
is really unnecessary. Now you can modify playWith
to check the value of self.kind
and change behavior, you can redefine playWith
to designate a playmate:
def playWith(self, who=None):
if who: pass
print self
t1.playWith(t2)
Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello"
that would probably end up as "H\0e\0l\0l\0o\0\0\0"
and your program would only print the 'H'
before it sees what it thinks is a null terminator.
So now you may wonder why it even compiles and links.
Well it compiles because you are allowed to define an overload to a function.
Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.
Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[])
version.
You cannot use php artisan
if you are not inside a laravel
project folder.
That is why it says 'Could not open input file - artisan'
.
Your x and y values ??are not running so first of all youre begin to write this point
import numpy as np
import pandas as pd
import matplotlib as plt
dataframe=pd.read_csv(".\datasets\Position_Salaries.csv")
x=dataframe.iloc[:,1:2].values
y=dataframe.iloc[:,2].values
x1=dataframe.iloc[:,:-1].values
point of value have publish
the fancy answer. Use std::vector and search with std::find
the simple answer
use a for loop
First convert this structure to a "dictionary" object:
dict = {}
json.forEach(function(x) {
dict[x.code] = x.name
})
and then simply
countryName = dict[countryCode]
For a list of countries this doesn't matter much, but for larger lists this method guarantees the instant lookup, while the naive searching will depend on the list size.
Instead of initiating a background process, what about creating a trigger file and having a scheduler like cron or autosys periodically execute a script that looks for and acts on the trigger files? The triggers could contain instructions or even raw commands (better yet, just make it a shell script).
This will search all the related files in current and sub directories, calculating their line count separately as well as totally:
find . -name "*.wanted" | xargs wc -l
That didn't work for me, I used some code parts from web, what I did:
new activity: FullScreenImage with:
package yourpackagename;
import yourpackagename.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class FullScreenImage extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_full);
Bundle extras = getIntent().getExtras();
Bitmap bmp = (Bitmap) extras.getParcelable("imagebitmap");
ImageView imgDisplay;
Button btnClose;
imgDisplay = (ImageView) findViewById(R.id.imgDisplay);
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FullScreenImage.this.finish();
}
});
imgDisplay.setImageBitmap(bmp );
}
}
Then create a xml: layout_full
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/imgDisplay"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter" />
<Button
android:id="@+id/btnClose"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="15dp"
android:layout_marginTop="15dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:textColor="#ffffff"
android:text="Close" />
</RelativeLayout>
And finally, send the image name from your mainactivity
final ImageView im = (ImageView)findViewById(R.id.imageView1) ;
im.setBackgroundDrawable(getResources().getDrawable(id1));
im.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(NAMEOFYOURCURRENTACTIVITY.this, FullScreenImage.class);
im.buildDrawingCache();
Bitmap image= im.getDrawingCache();
Bundle extras = new Bundle();
extras.putParcelable("imagebitmap", image);
intent.putExtras(extras);
startActivity(intent);
}
});
You can use jQuery each function as it is explained below:
Define your data:
var jsonStr = '[{"name":"Lenovo Thinkpad 41A4298,"website":"google"},{"name":"Lenovo Thinkpad 41A2222,"website":"google"},{"name":"Lenovo Thinkpad 41Awww33,"website":"yahoo"},{"name":"Lenovo Thinkpad 41A424448,"website":"google"},{"name":"Lenovo Thinkpad 41A429rr8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ff8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ss8,"website":"rediff"},{"name":"Lenovo Thinkpad 41A429sg8,"website":"yahoo"}]';
Parse JSON string to JSON object:
var json = JSON.parse(jsonStr);
Iterate and filter:
$.each(JSON.parse(json), function (idx, obj) {
if (obj.website == 'yahoo') {
// do whatever you want
}
});
Here is a great article using Restkit
It explains on serializing nested data into JSON and attaching the data to a HTTP POST request.
instead of using jsonObject try using CsvSchema its way easier and directly converts object to csv
CsvSchema schema = csvMapper.schemaFor(MyClass.class).withHeader();
csvMapper.writer(schema).writeValueAsString(myClassList);
and it mentains the order id your pojo has @JsonPropertyOrder in it
See this blog article that describes the difference. Basically doing:
Task.Run(A)
Is the same as doing:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
SCREEN:
NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo
or printf
I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)
You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:
screen /dev/ttyS0 19200,cs8
(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.
ECHO:
Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0
) while I was sending the echo command.
PRINTF:
I found that one can also use printf's '%x' command:
c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT
Again, for printf, start cat < /dev/ttyS0
before sending the command.
FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.
Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).
Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.
You can use a struct to read write into a file. You do not need to cast it as a `char*. Struct size will also be preserved. (This point is not closest to the topic but guess it: behaving on hard memory is often similar to RAM one.)
To move (to & from) a single string field you must use strncpy
and a transient string buffer '\0'
terminating.
Somewhere you must remember the length of the record string field.
To move other fields you can use the dot notation, ex.:
NodeB->one=intvar;
floatvar2=(NodeA->insidebisnode_subvar).myfl;
struct mynode {
int one;
int two;
char txt3[3];
struct{char txt2[6];}txt2fi;
struct insidenode{
char txt[8];
long int myl;
void * mypointer;
size_t myst;
long long myll;
} insidenode_subvar;
struct insidebisnode{
float myfl;
} insidebisnode_subvar;
} mynode_subvar;
typedef struct mynode* Node;
...(main)
Node NodeA=malloc...
Node NodeB=malloc...
You can embed each string into a structs that fit it,
to evade point-2 and behave like Cobol:
NodeB->txt2fi=NodeA->txt2fi
...but you will still need of a transient string
plus one strncpy
as mentioned at point-2 for scanf
, printf
otherwise an operator longer input (shorter),
would have not be truncated (by spaces padded).
(NodeB->insidenode_subvar).mypointer=(NodeA->insidenode_subvar).mypointer
will create a pointer alias.NodeB.txt3=NodeA.txt3
causes the compiler to reject:
error: incompatible types when assigning to type ‘char[3]’ from type ‘char *’
point-4 works only because NodeB->txt2fi
& NodeA->txt2fi
belong to the same typedef
!!
A correct and simple answer to this topic I found at In C, why can't I assign a string to a char array after it's declared? "Arrays (also of chars) are second-class citizens in C"!!!
$watch first parameter can be angular expression or function. See documentation on $scope.$watch. It contains a lot of useful info about how $watch method works: when watchExpression is called, how angular compares results, etc.
It's not bad practice at all. They are usually referred as SUBQUERY, SUBSELECT or NESTED QUERY.
It's a relatively expensive operation, but it's quite common to encounter a lot of subqueries when dealing with databases since it's the only way to perform certain kind of operations on data.
You're trying to insert $newdate
into your db. You need to convert it to a string first. Use the DateTime::format
method to convert back to a string.
if symfony version less than 2.8
sudo chmod -R 777 app/cache/*
_x000D_
if symfony version great than or equal 3.0
sudo chmod -R 777 var/cache/*
_x000D_
Keyguard basically refers to the code that handles the unlocking of the phone. it's like the keypad lock on your nokia phone a few years back just with the utility on a touchscreen.
you can find more info it you look in android/app
or com\android\internal\policy\impl
Good Luck !
Wrap all the children inside of another LinearLayout with wrap_content
for both the width and the height as well as the vertical orientation.
Here is my solution:
#include <fstream>
int main()
{
std::ofstream ("Hello.txt");
return 0;
}
File (Hello.txt) is created even without ofstream name, and this is the difference from Mr. Boiethios answer.
@media print{_x000D_
body{_x000D_
visibility: hidden; /* no print*/_x000D_
}_x000D_
.print{_x000D_
_x000D_
visibility:visible; /*print*/_x000D_
}_x000D_
}
_x000D_
<body>_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="print"> <!---print--->_x000D_
<div class="print"> <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
As the question is asked years ago, and Android is evolved a lot on this URI scheme.
From original URI scheme, to deep link, and now Android App Links.
Android now recommends to use HTTP URLs, not define your own URI scheme. Because Android App Links use HTTP URLs that link to a website domain you own, so no other app can use your links. You can check the comparison of deep link and Android App links from here
Now you can easily add a URI scheme by using Android Studio option: Tools > App Links Assistant. Please refer the detail to Android document: https://developer.android.com/studio/write/app-link-indexing.html
It is due permission problem,
sudo chown -R $USER /path to your python installed directory
/usr/local/lib/python2.7/
or try,
pip install --user -r package_name
and then say, pip install -r requirements.txt
this will install inside your env
dont say, sudo pip install -r requirements.txt
this is will install into arbitrary python path.
Two ways:
Use indexes:
double sum = 0;
for(int i = 0; i < m.size(); i++)
sum += m.get(i);
return sum;
Use the "for each" style:
double sum = 0;
for(Double d : m)
sum += d;
return sum;
A simple solution is to use Microsoft ASP.NET Web API 2.2 Client
from NuGet.
Then you can simply do this and it'll serialize the object to JSON and set the Content-Type
header to application/json; charset=utf-8
:
var data = new
{
name = "Foo",
category = "article"
};
var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var response = await client.PostAsJsonAsync("", data);
You will need to cast or convert the values to decimal before division. Take a look at this http://msdn.microsoft.com/en-us/library/aa226054.aspx
For example
DECLARE @num1 int = 3 DECLARE @num2 int = 2
SELECT @num1/@num2
SELECT @num1/CONVERT(decimal(4,2), @num2)
The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000
Unfortunately, np.polynomial.polynomial.polyfit
returns the coefficients in the opposite order of that for np.polyfit
and np.polyval
(or, as you used np.poly1d
). To illustrate:
In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]:
array([ 84.29340848, -100.53595376, 44.83281408, -8.85931101,
0.65459882])
In [41]: np.polyfit(x, y, 4)
Out[41]:
array([ 0.65459882, -8.859311 , 44.83281407, -100.53595375,
84.29340846])
In general: np.polynomial.polynomial.polyfit
returns coefficients [A, B, C]
to A + Bx + Cx^2 + ...
, while np.polyfit
returns: ... + Ax^2 + Bx + C
.
So if you want to use this combination of functions, you must reverse the order of coefficients, as in:
ffit = np.polyval(coefs[::-1], x_new)
However, the documentation states clearly to avoid np.polyfit
, np.polyval
, and np.poly1d
, and instead to use only the new(er) package.
You're safest to use only the polynomial package:
import numpy.polynomial.polynomial as poly
coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)
Or, to create the polynomial function:
ffit = poly.Polynomial(coefs) # instead of np.poly1d
plt.plot(x_new, ffit(x_new))
The last 9 elements can be read from left to right using numlist[-9:], or from right to left using numlist[:-10:-1], as you want.
>>> a=range(17)
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[-9:]
[8, 9, 10, 11, 12, 13, 14, 15, 16]
>>> print a[:-10:-1]
[16, 15, 14, 13, 12, 11, 10, 9, 8]
If your Rails version is between > 3.1.0
and < 4
, place your fonts in any of the these folders:
app/assets/fonts
lib/assets/fonts
vendor/assets/fonts
For Rails versions > 4
, you must place your fonts in the app/assets/fonts
folder.
Note: To place fonts outside of these designated folders, use the following configuration:
config.assets.precompile << /\.(?:svg|eot|woff|ttf)\z/
For Rails versions > 4.2
, it is recommended to add this configuration to config/initializers/assets.rb
.
However, you can also add it to either config/application.rb
, or to config/production.rb
Declare your font in your CSS file:
@font-face {
font-family: 'Icomoon';
src:url('icomoon.eot');
src:url('icomoon.eot?#iefix') format('embedded-opentype'),
url('icomoon.svg#icomoon') format('svg'),
url('icomoon.woff') format('woff'),
url('icomoon.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
Make sure your font is named exactly the same as in the URL portion of the declaration. Capital letters and punctuation marks matter. In this case, the font should have the name icomoon
.
If you are using Sass or Less with Rails > 3.1.0
(your CSS file has .scss
or .less
extension), then change the url(...)
in the font declaration to font-url(...)
.
Otherwise, your CSS file should have the extension .css.erb
, and the font declaration should be url('<%= asset_path(...) %>')
.
If you are using Rails > 3.2.1
, you can use font_path(...)
instead of asset_path(...)
. This helper does exactly the same thing but it's more clear.
Finally, use your font in your CSS like you declared it in the font-family
part. If it was declared capitalized, you can use it like this:
font-family: 'Icomoon';
We can use __call__
method to use other class methods as static methods.
class _Callable:
def __init__(self, anycallable):
self.__call__ = anycallable
class Model:
def get_instance(conn, table_name):
""" do something"""
get_instance = _Callable(get_instance)
provs_fac = Model.get_instance(connection, "users")
Make sure you have package.json
inside root of your project.
Happy coding :)
As you have figured out that you cannot do it the way you have done in Java (or C#). Here is another suggestion, you could pass in the reference of the object as an argument and return bool value. If the result is found in your collection, you could assign it to the reference being passed and return ‘true’, otherwise return ‘false’. Please consider this code.
typedef std::map<string, Operator> OPERATORS_MAP;
bool OperatorList::tryGetOperator(string token, Operator& op)
{
bool val = false;
OPERATORS_MAP::iterator it = m_operators.find(token);
if (it != m_operators.end())
{
op = it->second;
val = true;
}
return val;
}
The function above has to find the Operator against the key 'token', if it finds the one it returns true and assign the value to parameter Operator& op.
The caller code for this routine looks like this
Operator opr;
if (OperatorList::tryGetOperator(strOperator, opr))
{
//Do something here if true is returned.
}
infowindow.open(null,null);
will close opened infowindow. It will work same as
Just subtract the two dates:
select date '2000-01-02' - date '2000-01-01' as dateDiff
from dual;
The result will be the difference in days.
More details are in the manual:
https://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements001.htm#i48042
this is old but for help :
you can also use the stringReader stream
string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );
In SQL, you escape a quote by another quote:
SELECT 'Alex''s Tea Factory' FROM DUAL
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:
startInfo.Verb = "runas";
This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.
This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.
Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
I would like to add to the answers of BalusC and Pascal Thivent another common use of insertable=false, updatable=false
:
Consider a column that is not an id but some kind of sequence number. The responsibility for calculating the sequence number may not necessarily belong to the application.
For example, sequence number starts with 1000 and should increment by one for each new entity. This is easily done, and very appropriately so, in the database, and in such cases these configurations makes sense.
Use numpy.concatenate(list1 , list2)
or numpy.append()
Look into the thread at Append a NumPy array to a NumPy array.
If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.
Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.
In your case it could be :
objContentLine = (from q in db.qryContents
where q.LineID == Value
orderby q.RowID descending
select q).FirstOrDefault();
Errors:
Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type
Error 242 Delegate 'System.Func<..>' does not take 1 arguments
Error 243 The name 'Value' does not exist in the current context
Fix the "Value" variable error and the other errors will also disappear.
The code
my_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
print t
prints
(1, 2)
(3, 4)
(5, 6)
The loop iterates over my_list
, and assigns the elements of my_list
to t
one after the other. The elements of my_list
happen to be tuples, so t
will always be a tuple. To access the first element of the tuple t
, use t[0]
:
for t in my_list:
print t[0]
To access the first element of the tuple at the given index i
in the list, you can use
print my_list[i][0]
For me a Reference to a WebService is a
SERVICE REFERENCE
.
Anyway it's very easy. As someone said, you just have to change the URL in the web.config file.
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="YourServiceSoap" />
</basicHttpBinding>
</bindings>
<client>
**** CHANGE THE LINE BELOW TO CHANGE THE URL ****
<endpoint address="http://10.10.10.100:8080/services/YourService.asmx"
binding="basicHttpBinding" bindingConfiguration="YourServiceSoap"
contract="YourServiceRef.YourServiceSoap" name="YourServiceSoap" />
</client>
pandas 0.21 introduces new functions for Parquet:
pd.read_parquet('example_pa.parquet', engine='pyarrow')
or
pd.read_parquet('example_fp.parquet', engine='fastparquet')
The above link explains:
These engines are very similar and should read/write nearly identical parquet format files. These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).
it depends if your div is in position: absolute / fixed or relative / static
for position: absolute & fixed
<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>
The trick here is to have a negative margin half the width of the object
for position: relative & static
<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>
for both techniques, it is imperative to set the width.
Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row
:
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
You could then access one:
MyStringArrays.ElementAt(0)[1]
If you use linqpad, here is a very simple scenario of your example:
class Datatable
{
public List<data> rows { get; set; }
public Datatable(){
rows = new List<data>();
}
}
class data
{
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}
void Main()
{
var datatable = new Datatable();
var r = new data();
r.Name = "Jim";
r.Address = "USA";
r.Age = 23;
datatable.rows.Add(r);
List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
{
MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
}
var s = MyStringArrays.ElementAt(0)[1];
Console.Write(s);//"USA"
}
Prim's is better for more dense graphs, and in this we also do not have to pay much attention to cycles by adding an edge, as we are primarily dealing with nodes. Prim's is faster than Kruskal's in the case of complex graphs.
#!/bin/bash
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"
# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"
# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer
or:
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
Given a command like attrib
:
require 'open3'
a="attrib"
Open3.popen3(a) do |stdin, stdout, stderr|
puts stdout.read
end
I've found that while this method isn't as memorable as
system("thecommand")
or
`thecommand`
in backticks, a good thing about this method compared to other methods is
backticks don't seem to let me puts
the command I run/store the command I want to run in a variable, and system("thecommand")
doesn't seem to let me get the output whereas this method lets me do both of those things, and it lets me access stdin, stdout and stderr independently.
See "Executing commands in ruby" and Ruby's Open3 documentation.
Eclipse is looking for eclipse projects, meaning its is searching for eclipse-specific files in the root directory, namely .project
and .classpath
. You either gave Eclipse the wrong directory (if you are importing a eclipse project) or you actually want to create a new project from existing source(new
->java project
->create project from existing source
).
I think you probably want the second one, because Eclipse projects usually have separate source & build directories. If your sources and .class files are in the same directory, you probably didn't have a eclipse project.
You can get this with .BuiltInDocmementProperties
.
For example:
Public Sub PrintDocumentProperties()
Dim oApp As New Excel.Application
Dim oWB As Workbook
Set oWB = ActiveWorkbook
Dim title As String
title = oWB.BuiltinDocumentProperties("Title")
Dim lastauthor As String
lastauthor = oWB.BuiltinDocumentProperties("Last Author")
Debug.Print title
Debug.Print lastauthor
End Sub
See this page for all the fields you can access with this: http://msdn.microsoft.com/en-us/library/bb220896.aspx
If you're trying to do this outside of the client (i.e. with Excel closed and running code from, say, a .NET program), you need to use DSOFile.dll.
Yes you can access them. You should declare them in 'public space' (outside any functions) as:
var globalvar1 = 'value';
You can access them later on, also in other files.
I instinctively read it as "different from". "!=" hits me milliseconds after.
In my case the same Model was used in many pages for re-usability purposes. So what i did was i have created a custom attribute which checks for exclusions
public class ValidateAttribute : ActionFilterAttribute
{
public string Exclude { get; set; }
public string Base { get; set; }
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!string.IsNullOrWhiteSpace(this.Exclude))
{
string[] excludes = this.Exclude.Split(',');
foreach (var exclude in excludes)
{
actionContext.ModelState.Remove(Base + "." + exclude);
}
}
if (actionContext.ModelState.IsValid == false)
{
var mediaType = new MediaTypeHeaderValue("application/json");
var error = actionContext.ModelState;
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, error.Keys, mediaType);
}
}
}
and in your controller
[Validate(Base= "person",Exclude ="Age,Name")]
public async Task<IHttpActionResult> Save(User person)
{
//do something
}
Say the Model is
public class User
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(18,99)]
public string Age { get; set; }
[MaxLength(250)]
public string Address { get; set; }
}
There are 3 ways I can think of:
The way that is easiest to explain is
:%s/phrase to delete//gc
but you can also (personally I use this second one more often) do a regular search for the phrase to delete
/phrase to delete
Vim will take you to the beginning of the next occurrence of the phrase.
Go into insert mode (hit i) and use the Delete key to remove the phrase.
Hit escape when you have deleted all of the phrase.
Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed
Continue hitting n and dot until you are done.
Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you
Count the number of characters you want to delete
Type that number in (with number keys)
Hit the x key - characters should get deleted
Continue through with n and dot like in the second method.
PS - And if you didn't know already you can do a capital n to move backwards through the search matches.
Avoids using either shift
or a for
cycle at the cost of size and readability.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
set /a arg_idx=1
set "curr_arg_value="
:loop1
if !arg_idx! GTR 9 goto :done
set curr_arg_label=%%!arg_idx!
call :get_value curr_arg_value !curr_arg_label!
if defined curr_arg_value (
echo/!curr_arg_label!: !curr_arg_value!
set /a arg_idx+=1
goto :loop1
)
:done
set /a cnt=!arg_idx!-1
echo/argument count: !cnt!
endlocal
goto :eof
:get_value
(
set %1=%2
)
Output:
count_cmdline_args.bat testing more_testing arg3 another_arg
%1: testing
%2: more_testing
%3: arg3
%4: another_arg
argument count: 4
EDIT: The "trick" used here involves:
Constructing a string that represents a currently evaluated command-line argument variable (i.e. "%1", "%2" etc.) using a string that contains a percent character (%%
) and a counter variable arg_idx
on each loop iteration.
Storing that string into a variable curr_arg_label
.
Passing both that string (!curr_arg_label!
) and a return variable's name (curr_arg_value
) to a primitive subprogram get_value
.
In the subprogram its first argument's (%1
) value is used on the left side of assignment (set
) and its second argument's (%2
) value on the right. However, when the second subprogram's argument is passed it is resolved into value of the main program's command-line argument by the command interpreter. That is, what is passed is not, for example, "%4" but whatever value the fourth command-line argument variable holds ("another_arg" in the sample usage).
Then the variable given to the subprogram as return variable (curr_arg_value
) is tested for being undefined, which would happen if currently evaluated command-line argument is absent. Initially this was a comparison of the return variable's value wrapped in square brackets to empty square brackets (which is the only way I know of testing program or subprogram arguments which may contain quotes and was an overlooked leftover from trial-and-error phase) but was since fixed to how it is now.
If you have "something" and need 'something', use replace(col, "\"", "\'")
and viceversa.
This will allow file names to have spaces (reproducible example).
# Select files of interest, here, only text files for ex.
find -type f -exec file {} \; > findresult.txt
grep ": ASCII text$" findresult.txt > textfiles.txt
# leave only the path to the file removing suffix and prefix
sed -i -e 's/:.*$//' textfiles.txt
sed -i -e 's/\.\///' textfiles.txt
#write a script that deletes the files in textfiles.txt
IFS_backup=$IFS
IFS=$(echo "\n\b")
for f in $(cat textfiles.txt);
do
rm "$f";
done
IFS=$IFS_backup
# save script as "some.sh" and run: sh some.sh
The main problem you're having is that you're learning programming for the first time with Java and I think Java isn't the best language to start.
I suppose that you're addressing a work project, Is this the case? That pressure might make things worse. Depending on how complex the project is you might success but learning Java in 10 weeks without background knowledge is another issue.
SELECT * FROM items WHERE `items.xml` LIKE '%123456%'
The %
operator in LIKE
means "anything can be here".
If you spot the use of eval() in your code, remember the mantra “eval() is evil.”
This function takes an arbitrary string and executes it as JavaScript code. When the code in question is known beforehand (not determined at runtime), there’s no reason to use eval(). If the code is dynamically generated at runtime, there’s often a better way to achieve the goal without eval(). For example, just using square bracket notation to access dynamic properties is better and simpler:
// antipattern
var property = "name";
alert(eval("obj." + property));
// preferred
var property = "name";
alert(obj[property]);
Using eval()
also has security implications, because you might be executing code (for
example coming from the network) that has been tampered with.
This is a common antipattern when dealing with a JSON response from an Ajax request.
In those cases
it’s better to use the browsers’ built-in methods to parse the JSON response to make
sure it’s safe and valid. For browsers that don’t support JSON.parse()
natively, you can
use a library from JSON.org.
It’s also important to remember that passing strings to setInterval()
, setTimeout()
,
and the Function()
constructor is, for the most part, similar to using eval()
and therefore
should be avoided.
Behind the scenes, JavaScript still has to evaluate and execute the string you pass as programming code:
// antipatterns
setTimeout("myFunc()", 1000);
setTimeout("myFunc(1, 2, 3)", 1000);
// preferred
setTimeout(myFunc, 1000);
setTimeout(function () {
myFunc(1, 2, 3);
}, 1000);
Using the new Function() constructor is similar to eval() and should be approached
with care. It could be a powerful construct but is often misused.
If you absolutely must
use eval()
, you can consider using new Function() instead.
There is a small potential benefit because the code evaluated in new Function() will be running in a local function scope, so any variables defined with var in the code being evaluated will not become globals automatically.
Another way to prevent automatic globals is to wrap the
eval()
call into an immediate function.
In Bluetooth, all objects are identified by UUIDs. These include services, characteristics and many other things. Bluetooth maintains a database of assigned numbers for standard objects, and assigns sub-ranges for vendors (that have paid enough for a reservation). You can view this list here:
https://www.bluetooth.com/specifications/assigned-numbers/
If you are implementing a standard service (e.g. a serial port, keyboard, headset, etc.) then you should use that service's standard UUID - that will allow you to be interoperable with devices that you didn't develop.
If you are implementing a custom service, then you should generate unique UUIDs, in order to make sure incompatible third-party devices don't try to use your service thinking it is something else. The easiest way is to generate random ones and then hard-code the result in your application (and use the same UUIDs in the devices that will connect to your service, of course).
The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.
Here is the script https://github.com/kedarvj/mysqldumpsplitter
And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully
1 - Open the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid (take note to revert this change on step 6)
Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox
Change:
<HardDisks>
<HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
To:
<HardDisks>
<HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
2 - Reboot machine
4 - Stop Virtual Machine (if started)
5 - On terminal:
su vbox
cd /home/virtualbox/WindowsServer/
VBoxManage modifyhd WindowsServer.vdi --resize SIZE
exit
exit
change SIZE for a number in Megabytes, example 80000 (80GB)
6 - Open again the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid whith the original value
Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox
Change:
<HardDisks>
<HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
To:
<HardDisks>
<HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
7 - Reboot machine
The default logging level is warning. Since you haven't changed the level, the root logger's level is still warning. That means that it will ignore any logging with a level that is lower than warning, including debug loggings.
This is explained in the tutorial:
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
The 'info' line doesn't print anything, because the level is higher than info.
To change the level, just set it in the root logger:
'root':{'handlers':('console', 'file'), 'level':'DEBUG'}
In other words, it's not enough to define a handler with level=DEBUG, the actual logging level must also be DEBUG in order to get it to output anything.
Please refer to the following method. It takes your date String as argument1, you need to specify the existing format of the date as argument2, and the result (expected) format as argument 3.
Refer to this link to understand various formats: Available Date Formats
public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {
String result = "";
SimpleDateFormat sdf;
SimpleDateFormat sdf1;
try {
sdf = new SimpleDateFormat(givenformat);
sdf1 = new SimpleDateFormat(resultformat);
result = sdf1.format(sdf.parse(date));
}
catch(Exception e) {
e.printStackTrace();
return "";
}
finally {
sdf=null;
sdf1=null;
}
return result;
}
If you want to export just single table, or subset of data from some table, you can do it directly from result window:
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
Run this command:
rvm get stable --auto-dotfiles
and make sure to read all the output. RVM
will tell you if something is wrong, which in your case might be because GEM_HOME
is set to something different then PATH
.
The two syntaxes are not equivalent and it can lead to unexpected errors. Here is a simple example showing the differences. If you have a model:
from django.db import models
class Test(models.Model):
added = models.DateTimeField(auto_now_add=True)
And you create a first object:
foo = Test.objects.create(pk=1)
Then you try to create an object with the same primary key:
foo_duplicate = Test.objects.create(pk=1)
# returns the error:
# django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")
foo_duplicate = Test(pk=1).save()
# returns the error:
# django.db.utils.IntegrityError: (1048, "Column 'added' cannot be null")
The largest django site I know of is the Washington Post, which would certainly indicate that it can scale well.
Good design decisions probably have a bigger performance impact than anything else. Twitter is often cited as a site which embodies the performance issues with another dynamic interpreted language based web framework, Ruby on Rails - yet Twitter engineers have stated that the framework isn't as much an issue as some of the database design choices they made early on.
Django works very nicely with memcached and provides some classes for managing the cache, which is where you would resolve the majority of your performance issues. What you deliver on the wire is almost more important than your backend in reality - using a tool like yslow is critical for a high performance web application. You can always throw more hardware at your backend, but you can't change your users bandwidth.
Try this:
INSERT INTO prices (
group,
id,
price
)
SELECT
7,
articleId,
1.50
FROM
article
WHERE
name LIKE 'ABC%';
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
hmmm, you can do it with a list comprehension. This would only make sense if you had a real range.. but it does do the job:
print([a for i in range(0,1) if b])
or using just those two variables:
print([a for a in range(a,a+1) if b])
Using the following imports:
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/delay';
Try this:
let fakeResponse = [1,2,3];
let delayedObservable = Observable.of(fakeResponse).delay(5000);
delayedObservable.subscribe(data => console.log(data));
UPDATE: RXJS 6
The above solution doesn't really work anymore in newer versions of RXJS (and of angular for example).
So the scenario is that I have an array of items to check with an API with. The API only accepts a single item, and I do not want to kill the API by sending all requests at once. So I need a timed release of items on the Observable stream with a small delay in between.
Use the following imports:
import { from, of } from 'rxjs';
import { delay } from 'rxjs/internal/operators';
import { concatMap } from 'rxjs/internal/operators';
Then use the following code:
const myArray = [1,2,3,4];
from(myArray).pipe(
concatMap( item => of(item).pipe ( delay( 1000 ) ))
).subscribe ( timedItem => {
console.log(timedItem)
});
It basically creates a new 'delayed' Observable for every item in your array. There are probably many other ways of doing it, but this worked fine for me, and complies with the 'new' RXJS format.
First of all this code snippet
char *addr=NULL;
strcpy(addr,retstring().c_str());
is invalid because you did not allocate memory where you are going to copy retstring().c_str().
As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.
Using just try_files
didn't work for me - it caused a rewrite or internal redirection cycle error in my logs.
The Nginx docs had some additional details:
http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
So I ended up using the following:
root /var/www/mysite;
location / {
try_files $uri /base.html;
}
location = /base.html {
expires 30s;
}
DataType
has a second constructor that takes a string. However, internally, this is actually the same as using the UIHint
attribute.
Adding a new core DataType is not possible since the DataType
enumeration is part of the .NET framework. The closest thing you can do is to create a new class that inherits from the DataTypeAttribute
. Then you can add a new constructor with your own DataType
enumeration.
public NewDataTypeAttribute(DataType dataType) : base(dataType)
{ }
public NewDataTypeAttribute(NewDataType newDataType) : base (newDataType.ToString();
You can also go through this link. But I will recommend you using Jquery for the same.
System.Text.Encoding.ChooseYourEncoding.GetString(bytes).ToCharArray();
Substitute the right encoding above: e.g.
System.Text.Encoding.UTF8.GetString(bytes).ToCharArray();
Maybe:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]
Computers store numbers in binary and can't actually represent numbers such as 33.333333333 or 100.0 exactly. This is one of the tricky things about using doubles. You will have to just round the answer before showing it to a user. Luckily in most applications, you don't need that many decimal places anyhow.
The problem is that your REGX pattern will only match the input "0-9".
To meet your requirement (0-9999999), you should rewrite your regx pattern:
ng-pattern="/^[0-9]{1,7}$/"
My example:
HTML:
<div ng-app ng-controller="formCtrl">
<form name="myForm" ng-submit="onSubmit()">
<input type="number" ng-model="price" name="price_field"
ng-pattern="/^[0-9]{1,7}$/" required>
<span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span>
<span ng-show="myForm.price_field.$error.required">This field is required!</span>
<input type="submit" value="submit"/>
</form>
</div>
JS:
function formCtrl($scope){
$scope.onSubmit = function(){
alert("form submitted");
}
}
Here is a jsFiddle demo.
If you are on Windows, use ipconfig to get the local IPv4 address, and then specify that under your Apache configuration file: httpd.conf, like:
Listen: 10.20.30.40:80
Restart your Apache server and test it from other computer on the network.
You can export collection by clicking on arrow button
and then click on download collection button
As @mikyra explained, creation date time is not stored anywhere.
All the methods above are nice, but if you want to quickly get only last modify date, you can type:
ls -lit /path
with -t option you list all file in /path odered by last modify date.
DECLARE @count_ser_temp int;
DECLARE @TableName AS VARCHAR(100)
SELECT @TableName = 'TableTemporal'
EXECUTE ('CREATE VIEW vTemp AS
SELECT *
FROM ' + @TableTemporal)
SELECT TOP 1 * INTO #servicios_temp FROM vTemp
DROP VIEW vTemp
-- Contar la cantidad de registros de la tabla temporal
SELECT @count_ser_temp = COUNT(*) FROM #servicios_temp;
-- Recorro los registros de la tabla temporal
WHILE @count_ser_temp > 0
BEGIN
END
END
In my scenario this was happening because I renamed a parameter in swagger.yaml
but did not reload the docs page.
Hence I was trying the API with an unexpected input parameter.
Long story short, F5 is my friend.
Long solved I'm sure but this might help some other poor soul.
This error can ocurre if the DLL you are deploying in the install package is not the same as the DLL you are referencing (these will have different IDs)
Sounds obvious but can easily happen if you make a small change to the dll and have previously installed the app on your own machine which reregisters the dll.
goto cpanel and login as Main Admin or Super Administrator
find SSH/Shell Access ( you will find under the security tab of cpanel )
now give the username and password of Super Administrator as root
or whatyougave
note: do not give any username, cos, it needs permissions
once your into console type
type ' mysql
' and press enter now you find youself in
mysql>
/* and type here like */
mysql> set global net_buffer_length=1000000;
Query OK, 0 rows affected (0.00 sec)
mysql> set global max_allowed_packet=1000000000;
Query OK, 0 rows affected (0.00 sec)
Now upload and enjoy!!!
You have to take into account that measuring the time that took a program to execute depends a lot on the load that the machine has in that specific moment.
Knowing that, the way of obtain the current time in C can be achieved in different ways, an easier one is:
#include <time.h>
#define CPU_TIME (getrusage(RUSAGE_SELF,&ruse), ruse.ru_utime.tv_sec + \
ruse.ru_stime.tv_sec + 1e-6 * \
(ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec))
int main(void) {
time_t start, end;
double first, second;
// Save user and CPU start time
time(&start);
first = CPU_TIME;
// Perform operations
...
// Save end time
time(&end);
second = CPU_TIME;
printf("cpu : %.2f secs\n", second - first);
printf("user : %d secs\n", (int)(end - start));
}
Hope it helps.
Regards!
All the validation from model are skipped when we use validate: false
user = User.new(....)
user.save(validate: false)
I just experienced the same problem using the virtual environment.
For me installing the package using python from the venv worked:
.\venv\environment\Scripts\python.exe -m pip install flask-sqlalchemy
I'd also suggest moving the event handler outside render.
var OnSubmitTest = React.createClass({
submit: function(e){
e.preventDefault();
alert('it works!');
}
render: function() {
return (
<form onSubmit={this.submit}>
<button>Click me</button>
</form>
);
}
});
Attribute_Brands is a named range that should contain your list items. Use the drop down to the left of the formula bar to jump to the named range, then edit it. If you add or remove items you will need to adjust the range the named range covers.
In postman - Have you tried adding the header element 'Accept' as 'application/vnd.ms-excel'
You're right yes. The architecture of a system is its 'skeleton'. It's the highest level of abstraction of a system. What kind of data storage is present, how do modules interact with each other, what recovery systems are in place. Just like design patterns, there are architectural patterns: MVC, 3-tier layered design, etc.
Software design is about designing the individual modules / components. What are the responsibilities, functions, of module x? Of class Y? What can it do, and what not? What design patterns can be used?
So in short, Software architecture is more about the design of the entire system, while software design emphasizes on module / component / class level.
Same thing happened to me and I got it working doing this:
This worked for me.
I will provide really simple solution to the problem.
Suppose we have two inputs username
and password
,but we want our handle to be easy and generic ,so we can reuse it and don't write boilerplate code.
I.Our form:
<form>
<input type="text" name = "username" onChange={this.onChange} value={this.state.username}/>
<input type="text" name = "password" onChange={this.onChange} value={this.state.password}/>
<br></br>
<button type="submit">Submit</button>
</form>
II.Our constructor ,which we want to save our username
and password
,so we can access them easily:
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
this.onSubmit = this.onSubmit.bind(this);
this.onChange = this.onChange.bind(this);
}
III.The interesting and "generic" handle with only one onChange
event is based on this:
onChange(event) {
let inputName = event.target.name;
let value = event.target.value;
this.setState({[inputName]:value});
event.preventDefault();
}
Let me explain:
1.When a change is detected the onChange(event)
is called
2.Then we get the name parameter of the field and its value:
let inputName = event.target.name; ex: username
let value = event.target.value; ex: itsgosho
3.Based on the name parameter we get our value from the state in the constructor and update it with the value:
this.state['username'] = 'itsgosho'
4.The key to note here is that the name of the field must match with our parameter in the state
Hope I helped someone somehow :)
You could read the entire file with dynamic memory allocation, but isn't a good idea because if the file is too big, you could have memory problems.
So is better read short parts of the file and print it.
#include <stdio.h>
#define BLOCK 1000
int main() {
FILE *f=fopen("teste.txt","r");
int size;
char buffer[BLOCK];
// ...
while((size=fread(buffer,BLOCK,sizeof(char),f)>0)
fwrite(buffer,size,sizeof(char),stdout);
fclose(f);
// ...
return 0;
}
By default, all paths you define will be relative. The question is: relative to what? There are several options:
Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.
[Note: edited to modernize ggplot syntax]
Your example is not reproducible since there is no ex1221new
(there is an ex1221
in Sleuth2
, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot
. One advantage is that ggplot
works with data.frame
s directly.
You can set the labels with xlab()
and ylab()
, or make it part of the scale_*.*
call.
library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
geom_point(aes(size=NO3)) +
scale_size_area() +
xlab("My x label") +
ylab("My y label") +
ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")
ggplot(ex1221, aes(Discharge, Area)) +
geom_point(aes(size=NO3)) +
scale_size_area("Nitrogen") +
scale_x_continuous("My x label") +
scale_y_continuous("My y label") +
ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")
An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs
function
ggplot(ex1221, aes(Discharge, Area)) +
geom_point(aes(size=NO3)) +
scale_size_area() +
labs(size= "Nitrogen",
x = "My x label",
y = "My y label",
title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")
which gives an identical figure to the one above.
It depends on what you are doing, and what you need.
If you are iterating through a collection of items, and do not care about the index values then foreach is more convenient, easier to write and safer: you can't get the number of items wrong.
If you need to process every second item in a collection for example, or process them ion the reverse order, then a for loop is the only practical way.
The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone. This means that a for loop can modify a collection - which is illegal and will cause an error in a foreach loop.
Pull Request - I've used most of the already submitted ideas but one that I also often use is ( especially if its from another dev ) doing a Pull Request which gives a handy way to review all of the changes in a merge before it takes place. I know that is GitHub not git but it sure is handy.
New to MySql myself and found this is happening on Windows as well. Goto Query > Explain Current Statement > click on the Results Grid icon on the far right of the Visual Explain window that shows by default. You may have to toggle through the up down arrow icons to see it.
You can map the strings to enum values, then switch on the enum:
enum Options {
Option_Invalid,
Option1,
Option2,
//others...
};
Options resolveOption(string input);
// ...later...
switch( resolveOption(input) )
{
case Option1: {
//...
break;
}
case Option2: {
//...
break;
}
// handles Option_Invalid and any other missing/unmapped cases
default: {
//...
break;
}
}
Resolving the enum can be implemented as a series of if
checks:
Options resolveOption(std::string input) {
if( input == "option1" ) return Option1;
if( input == "option2" ) return Option2;
//...
return Option_Invalid;
}
Or a map lookup:
Options resolveOption(std::string input) {
static const std::map<std::string, Option> optionStrings {
{ "option1", Option1 },
{ "option2", Option2 },
//...
};
auto itr = optionStrings.find(input);
if( itr != optionStrings.end() ) {
return *itr;
}
return Option_Invalid;
}
In swift 3, We can simply use DispatchQueue.main.asyncAfter function to trigger any function or action after the delay of 'n' seconds. Here in code we have set delay after 1 second. You call any function inside the body of this function which will trigger after the delay of 1 second.
let when = DispatchTime.now() + 1
DispatchQueue.main.asyncAfter(deadline: when) {
// Trigger the function/action after the delay of 1Sec
}
Let's get a canonical answer here. I will reference the HTML5 spec.
First of all, 12.1.2.4 Optional tags:
A
head
element's start tag may be omitted if the element is empty, or if the first thing inside thehead
element is an element.A
head
element's end tag may be omitted if thehead
element is not immediately followed by a space character or a comment.A
body
element's start tag may be omitted if the element is empty, or if the first thing inside thebody
element is not a space character or a comment, except if the first thing inside thebody
element is ascript
orstyle
element.A
body
element's end tag may be omitted if thebody
element is not immediately followed by a comment.
Then, the 4.1.1 The html element:
Content model: A
head
element followed by abody
element.
Having the cited restrictions and strictly defined element order, we can easily work out what are the rules for placing implicit <body>
tag.
Since <head/>
must come first, and it can contain elements only (and not direct text), all elements suitable for <head/>
will become the part of implicit <head/>
, up to the first stray text or <body/>
-specific element. At that moment, all remaining elements and text nodes will be placed in <body/>
.
Now let's consider your second snippet:
<html>
<header>...</header>
<body>
<section>...</section>
<section>...</section>
<section>...</section>
</body>
<footer>...</footer>
</html>
Here, the <header/>
element is not suitable for <head/>
(it's flow content), the <body>
tag will be placed immediately before it. In other words, the document will be understood by browser as following:
<html>
<head/>
<body>
<header>...</header>
<body>
<section>...</section>
<section>...</section>
<section>...</section>
</body>
<footer>...</footer>
</body>
</html>
And that's certainly not what you were expecting. And as a note, it is invalid as well; see 4.4.1 The body element:
Contexts in which this element can be used: As the second element in an
html
element.[...]
In conforming documents, there is only one
body
element.
Thus, the <header/>
or <footer/>
will be correctly used in this context. Well, they will be practically equivalent to the first snippet. But this will cause an additional <body/>
element in middle of a <body/>
which is invalid.
As a side note, you're probably confusing <body/>
here with the main part of the content which has no specific element. You could look up that page for other solutions on getting what you want.
Quoting 4.4.1 The body element once again:
The
body
element represents the main content of the document.
which means all the content. And both header and footer are part of this content.
If found this alteration to Krzysztof answer helped my issue
$('#' + parentId + ' .collapse').on('show.bs.collapse', function (e) {
var all = $('#' + parentId).find('.collapse');
var actives = $('#' + parentId).find('.in, .collapsing');
all.each(function (index, element) {
$(element).collapse('hide');
})
actives.each(function (index, element) {
$(element).collapse('show');
})
})
if you have nested panels then you may also need to specify which ones by adding another class name to distinguish between them and add this to the a selector in the above JavaScript
If you want to use Varun's ROBOCOPY command line in the Explorer context menu (i.e. right-click) here is a Windows registry import. I tried adding this as a comment to his answer, but the inline markup wasn't feasible.
I've tested this on my own Windows 10 PC, but use at your own risk. It will open a new command prompt, run the command, and pause so you can see the output.
Copy into a new text file:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\directory\Background\shell\Delete Empty Folders\command] @="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"
[HKEY_CURRENT_USER\Software\Classes\directory\shell\Delete Empty Folders\command] @="C:\Windows\System32\Cmd.exe /C \"C:\Windows\System32\Robocopy.exe \"%V\" \"%V\" /s /move\" && PAUSE"
Rename the .txt extension to .reg
As of October 2014:
For latest remote version:
npm view <module_name> version
Note, version is singular.
If you'd like to see all available (remote) versions, then do:
npm view <module_name> versions
Note, versions is plural. This will give you the full listing of versions to choose from.
To get the version you actually have locally you could use:
npm list --depth=0 | grep <module_name>
Note, even with package.json declaring your versions, the installed version might actually differ slightly - for instance if tilda was used in the version declaration
Should work across NPM versions 1.3.x, 1.4.x, 2.x and 3.x
I had a similar issue, but in my case, it was my CSS file.
I had loaded my CSS file before the JQuery library, since my jquery function was interaction with my css file, my jquery function wasn't working. I found this weird, but when I loaded the CSS file after loading the JQuery library, it worked.
This might not be directly related to the Question, but it may help others who might be facing a similar problem.
My issue:
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="slider.js"></script>
My solution:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="slider.js"></script>
Given:
A_1 = [10 200 7 150]';
A_2 = [0.001 0.450 0.007 0.200]';
(As others have already pointed out) There are tools to simply compute correlation, most obviously corr
:
corr(A_1, A_2); %Returns 0.956766573975184 (Requires stats toolbox)
You can also use base Matlab's corrcoef
function, like this:
M = corrcoef([A_1 A_2]): %Returns [1 0.956766573975185; 0.956766573975185 1];
M(2,1); %Returns 0.956766573975184
Which is closely related to the cov
function:
cov([condition(A_1) condition(A_2)]);
As you almost get to in your original question, you can scale and adjust the vectors yourself if you want, which gives a slightly better understanding of what is going on. First create a condition function which subtracts the mean, and divides by the standard deviation:
condition = @(x) (x-mean(x))./std(x); %Function to subtract mean AND normalize standard deviation
Then the correlation appears to be (A_1 * A_2)/(A_1^2), like this:
(condition(A_1)' * condition(A_2)) / sum(condition(A_1).^2); %Returns 0.956766573975185
By symmetry, this should also work
(condition(A_1)' * condition(A_2)) / sum(condition(A_2).^2); %Returns 0.956766573975185
And it does.
I believe, but don't have the energy to confirm right now, that the same math can be used to compute correlation and cross correlation terms when dealing with multi-dimensiotnal inputs, so long as care is taken when handling the dimensions and orientations of the input arrays.
Use:
find . ! -readable -prune -o -print
or more generally
find <paths> ! -readable -prune -o <other conditions like -name> -print
Works with: find (GNU findutils) 4.4.2. Background:
-readable
test matches readable files. The !
operator returns true, when test is false. And ! -readable
matches not readable directories (&files).-prune
action does not descend into directory.! -readable -prune
can be translated to: if directory is not readable, do not descend into it.-readable
test takes into account access control lists and other permissions artefacts which the -perm
test ignores.See also find
(1) manpage for many more details.
My solution will be to keep text part of tool bar separate, to define style and say, center or whichever alignment. It can be done in XML itself. Some paddings can be specified after doing calculations when you have actions that are visible always. I have moved two attributes from toolbar to its child TextView. This textView can be provided id to be accessed from fragments.
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" >
<!--android:theme="@style/defaultTitleTheme"
app:titleTextColor="@color/white"-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingStart="@dimen/icon_size"
android:text="@string/title_home"
style="@style/defaultTitleTheme"
tools:ignore="RtlSymmetry" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
You can get the icons from the android sdk they are in this folder
$android-sdk\platforms\android-xx\data\res
@niutech I was having the similar issue which is caused by Rocket Loader Module by Cloudflare. Just disable it for the website and it will sort out all your related issues.
Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times
According to your requirement :
1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD
When attempting to troubleshoot this problem with svcutil
, I received the error referred to in dblood's answer ("referenced type cannot be used since it does not match imported DataContract").
In my case the underlying cause seemed to be an enum type that had the DataContract attribute, but whose members were not marked with the EnumMember attribute. The problem class svcutil
pointed at had a property with that enum type.
This would fit better as a comment to dblood's answer, but not enough rep for that...
sort -u
will be slightly faster, because it does not need to pipe the output between two commands
also see my question on the topic: calling uniq and sort in different orders in shell
In JDK8
Stream<String> lines = Files.lines(path);
String data = lines.collect(Collectors.joining("\n"));
lines.close();
playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).
To solve your problem you can either make audioSounds static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:
SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
{
playsound = true;
}
}
If you have array like:
$runners = ["1","2","3","4"];
And if you want to covert them into integers and keep within array, following should do the job:
$newArray = array_map( create_function('$value', 'return (int)$value;'),
$runners);