Have you tried to remove the proxy username and password? A similar poster encountered that issue:
Failing that I found the following worked:
mvn dependency:resolve
Given a root Vue instance is accessible by all descendants via this.$root
, a parent component can access child components via the this.$children
array, and a child component can access it's parent via this.$parent
, your first instinct might be to access these components directly.
The VueJS documentation warns against this specifically for two very good reasons:
The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:
$on()
- allows you to declare a listener on your Vue instance with which to listen to events$emit()
- allows you to trigger events on the same instance (self)$on()
and $emit()
:const events = new Vue({}),_x000D_
parentComponent = new Vue({_x000D_
el: '#parent',_x000D_
ready() {_x000D_
events.$on('eventGreet', () => {_x000D_
this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;_x000D_
});_x000D_
},_x000D_
data: {_x000D_
parentMsg: 'I am listening for an event..',_x000D_
counter: 0_x000D_
}_x000D_
}),_x000D_
childComponent = new Vue({_x000D_
el: '#child',_x000D_
methods: {_x000D_
greet: function () {_x000D_
events.$emit('eventGreet');_x000D_
this.childMsg = `I am firing greeting event ${++this.counter} times..`;_x000D_
}_x000D_
},_x000D_
data: {_x000D_
childMsg: 'I am getting ready to fire an event.',_x000D_
counter: 0_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script>_x000D_
_x000D_
<div id="parent">_x000D_
<h2>Parent Component</h2>_x000D_
<p>{{parentMsg}}</p>_x000D_
</div>_x000D_
_x000D_
<div id="child">_x000D_
<h2>Child Component</h2>_x000D_
<p>{{childMsg}}</p>_x000D_
<button v-on:click="greet">Greet</button>_x000D_
</div>
_x000D_
Answer taken from the original post: Communicating between components in VueJS
When iterating over cell arrays of strings, the loop variable (let's call it f
) becomes a single-element cell array. Having to write f{1}
everywhere gets tedious, and modifying the loop variable provides a clean workaround.
% This example transposes each field of a struct.
s.a = 1:3;
s.b = zeros(2,3);
s % a: [1 2 3]; b: [2x3 double]
for f = fieldnames(s)'
s.(f{1}) = s.(f{1})';
end
s % a: [3x1 double]; b: [3x2 double]
% Redefining f simplifies the indexing.
for f = fieldnames(s)'
f = f{1};
s.(f) = s.(f)';
end
s % back to a: [1 2 3]; b: [2x3 double]
None of the other answers worked for me.
Make sure both unzipped files are in same folder, but also right click on setup.exe, select properties, compatibility, and then put a checkmark in "Run this program in compatibility mode for..." and select Windows 7.
I successfully launched the installer without the error message on Windows 10 for the 32-bit version of Oracle 11g release 2.
From: http://www-01.ibm.com/support/docview.wss?uid=swg21960606
And as an addendum to all answers, FYI: override
is not a keyword, but a special kind of identifier! It has meaning only in the context of declaring/defining virtual functions, in other contexts it's just an ordinary identifier. For details read 2.11.2 of The Standard.
#include <iostream>
struct base
{
virtual void foo() = 0;
};
struct derived : base
{
virtual void foo() override
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
int main()
{
base* override = new derived();
override->foo();
return 0;
}
Output:
zaufi@gentop /work/tests $ g++ -std=c++11 -o override-test override-test.cc
zaufi@gentop /work/tests $ ./override-test
virtual void derived::foo()
Consider making your route:
_files_manage:
pattern: /files/management/{project}/{user}
defaults: { _controller: AcmeTestBundle:File:manage }
since they are required fields. It will make your url's prettier, and be a bit easier to manage.
Your Controller would then look like
public function projectAction($project, $user)
You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.
You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.
If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.
In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.
I do not think that you can do this easily. you should consider this answer here:
How can I display a pdf document into a Webview?
basically you'll be able to see a pdf if it is hosted online via google documents, but not if you have it in your device (you'll need a standalone reader for that)
LaTeX will usually not indent the first paragraph of a section. This is standard typographical practice. However, if you really want to override this default setting, use the package indentfirst available on CTAN.
if you re in say my-project/app/somefolder
run in terminal cd ..
two times to get in my-project/
folder
In c++ (distant, dusty memory) I think it was a little easier to look at the code and understand arrays than it is in Java sometimes. Both are row major. This illustration worked for me in helping to understand.
Given this code for a 2d array of strings...
String[][] messages;
messages = new String[][] {
{"CAT","DOG","YIN","BLACK","HIGH","DAY"},
{"kitten","puppy","yang","white","low","night"}
};
int row = messages.length;
int col = messages[0].length;
Naming my ints as if it were a 2d array (row, col) we see the values.
row = (int) 2
col = (int) 6
The last two lines of code, where we try to determine size and set them to row
and col
does not look all that intuitive and its not necessarily right.
What youre really dealing with here is this (note new variable names to illustrate):
int numOfArraysIn = messages.length;
int numOfElementsIn0 = messages[0].length;
int numOfElementsIn1 = messages[1].length;
Where messages.length
tells you messages
holds two arrays. An array of arrays.
AND then messages[x].length
yields the size of each of the individual arrays 0
1
inside messages
.
numOfArraysIn = (int) 2
numOfElementsIn0 = (int) 6
numOfElementsIn1 = (int) 6
When we print with a for each loop....
for (String str : messages[0])
System.out.print(str);
for (String str : messages[1])
System.out.print(str);
CATDOGYINBLACKHIGHDAYkittenpuppyyangwhitelownight
Trying to drop the brackets and print like this gives an error
for (String str : messages)
System.out.print(str);
incompatible types: String[] cannot be converted to String
The above is important to understand while setting up loops that use .length
to limit the step thru the array.
For anyone struggling with Google API mimeType for *.csv files. I have found the list of MIME types for google api docs files (look at snipped result)
<table border="1"><thead><tr><th>Google Doc Format</th><th>Conversion Format</th><th>Corresponding MIME type</th></tr></thead><tbody><tr><td>Documents</td><td>HTML</td><td>text/html</td></tr><tr></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td></td><td>Rich text</td><td>application/rtf</td></tr><tr><td></td><td>Open Office doc</td><td>application/vnd.oasis.opendocument.text</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>MS Word document</td><td>application/vnd.openxmlformats-officedocument.wordprocessingml.document</td></tr><tr><td></td><td>EPUB</td><td>application/epub+zip</td></tr><tr><td>Spreadsheets</td><td>MS Excel</td><td>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</td></tr><tr><td></td><td>Open Office sheet</td><td>application/x-vnd.oasis.opendocument.spreadsheet</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>CSV (first sheet only)</td><td>text/csv</td></tr><tr><td></td><td>TSV (first sheet only)</td><td>text/tab-separated-values</td></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr></tr><tr><td>Drawings</td><td>JPEG</td><td>image/jpeg</td></tr><tr><td></td><td>PNG</td><td>image/png</td></tr><tr><td></td><td>SVG</td><td>image/svg+xml</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td>Presentations</td><td>MS PowerPoint</td><td>application/vnd.openxmlformats-officedocument.presentationml.presentation</td></tr><tr><td></td><td>Open Office presentation</td><td>application/vnd.oasis.opendocument.presentation</td></tr><tr></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td>Apps Scripts</td><td>JSON</td><td>application/vnd.google-apps.script+json</td></tr></tbody></table>
_x000D_
Source here: https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents the table under: "Google Doc formats and supported export MIME types map to each other as follows"
There is also another list
<table border="1"><thead><tr><th>MIME Type</th><th>Description</th></tr></thead><tbody><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>audio</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>document</span></code></td><td>Google Docs</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drawing</span></code></td><td>Google Drawing</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>file</span></code></td><td>Google Drive file</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>folder</span></code></td><td>Google Drive folder</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>form</span></code></td><td>Google Forms</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>fusiontable</span></code></td><td>Google Fusion Tables</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>map</span></code></td><td>Google My Maps</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>photo</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>presentation</span></code></td><td>Google Slides</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>script</span></code></td><td>Google Apps Scripts</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>site</span></code></td><td>Google Sites</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>spreadsheet</span></code></td><td>Google Sheets</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>unknown</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>video</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drive-sdk</span></code></td><td>3rd party shortcut</td></tr></tbody></table>
_x000D_
Source here: https://developers.google.com/drive/v3/web/mime-types
But the first one was more helpful for my use case..
Happy coding ;)
The GNU Coding Standard is a good reference for things like this. This section deals with the output of --help
. In this case it is not very specific. You probably can't go wrong with printing a table showing the short and long options and a succinct description. Try to get the spacing between all arguments right for readability. You probably want to provide a man
page (and possibly an info
manual) for your tool to provide a more elaborate explanation.
I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.
Here is a simpler solution. Override the onTouch()
for the ScrollView
OnTouchListener
and return false if you want to bypass the scroll by touch. The programmatic scrolling still works and no need to extend the ScrollView
class.
mScroller.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return isScrollable;
}
});
When I'm converting from JSX to TSX and we keep some libraries as js/jsx and convert others to ts/tsx I almost always forget to change the js/jsx import statements in the TSX\TS files from
import * as ComponentName from "ComponentName";
to
import ComponentName from "ComponentName";
If calling an old JSX (React.createClass) style component from TSX, then use
var ComponentName = require("ComponentName")
I just run npm install
and then ok.
I think you've answered your own question: try not to go beyond the 70 Mb limit, however it really depends on many things: what iOS version you're using (not SDK), how many applications running in background, what exact memory you're using etc.
Just avoid the instant memory splashes (e.g. you're using 40 Mb of RAM, and then allocating 80 Mb's more for some short computation). In this case iOS would kill your application immediately.
You should also consider lazy loading of assets (load them only when you really need and not beforehand).
while not any( x in ('AND','OR','NOT') for x in list)
EDIT:
thank you for the upvotes , but etarion's solution is better since it tests if the words AND, OR, NOT are in the list, that is to say 3 tests.
Mine does as many tests as there are words in list.
EDIT2:
Also there is
while not ('AND' in list,'OR' in list,'NOT' in list)==(False,False,False)
Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux
The problem with your macro is that once you have opened your destination Workbook (xlw
in your code sample), it is set as the ActiveWorkbook object and you get an error because TextBox1 doesn't exist in that specific Workbook. To resolve this issue, you could define a reference object to your actual Workbook before opening the other one.
Sub UploadData()
Dim xlo As New Excel.Application
Dim xlw As New Excel.Workbook
Dim myWb as Excel.Workbook
Set myWb = ActiveWorkbook
Set xlw = xlo.Workbooks.Open("c:\myworkbook.xlsx")
xlo.Worksheets(1).Cells(2, 1) = myWb.ActiveSheet.Range("d4").Value
xlo.Worksheets(1).Cells(2, 2) = myWb.ActiveSheet.TextBox1.Text
xlw.Save
xlw.Close
Set xlo = Nothing
Set xlw = Nothing
End Sub
If you prefer, you could also use myWb.Activate
to put back your main Workbook as active. It will also work if you do it with a Worksheet object. Using one or another mostly depends on what you want to do (if there are multiple sheets, etc.).
1st option
if you want to set your custom storyboard instead of a default view controller.
Change this attribute from info.plist file
<key>UISceneStoryboardFile</key>
<string>Onboarding</string>
Onboarding would be your storyboard name
to open this right-click on info.plist file and open as a source code
2nd option
1- Click on your project
2- Select your project from the target section
3- Move to Deployment interface section
4- Change your storyboard section from Main Interface field
Please remember set your storyboard initial view controller
A variation of the existing answers:
Swift 5.1:
extension String {
func localized(withComment comment: String? = nil) -> String {
return NSLocalizedString(self, comment: comment ?? "")
}
}
You can then simply use it with or without comment:
"Goodbye".localized()
"Hello".localized(withComment: "Simple greeting")
Please note that genstrings
won't work with this solution.
Just specify it in shared.loader
or common.loader
property of /conf/catalina.properties
.
string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");
The first parameter is the path. The second is the search pattern you want to use.
You can use CSS's before pseudo.
.dateclass {
width: 100%;
}
.dateclass.placeholderclass::before {
width: 100%;
content: attr(placeholder);
}
.dateclass.placeholderclass:hover::before {
width: 0%;
content: "";
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input
type="date"
placeholder="Please specify a date"
onClick="$(this).removeClass('placeholderclass')"
class="dateclass placeholderclass">
_x000D_
Getting one char from string at specified index
Dim pos As Integer
Dim outStr As String
pos = 2
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)
outStr="b"
First you need to define a LocationListener
to handle location changes.
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
//your code here
}
};
Then get the LocationManager
and ask for location updates
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_REFRESH_TIME,
LOCATION_REFRESH_DISTANCE, mLocationListener);
}
And finally make sure that you have added the permission on the Manifest,
For using only network based location use this one
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
For GPS based location, this one
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
Since you don't want to add a class to cells containing an icon, how about this...
Wrap the contents of each non-icon td
in a span
:
<td><span>consectetur</span></td>
<td><span>adipiscing</span></td>
<td><span>elit</span></td>
And use this CSS:
td {
text-align: center;
}
td span {
text-align: left;
display: block;
}
I wouldn't normally post an answer in this situation, but this seems too long for a comment.
This type of error occurs when the datatype of the SQL Server column has a length which is less than the length of the data entered into the entry form.
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
From the Oracle documentation page about multiple inheritance type,we can find the accurate answer here. Here we should first know the type of multiple inheritance in java:-
Java "doesn't support the multiple inheritance of state, but it support multiple inheritance of implementation with default methods since java 8 release and multiple inheritance of type with interfaces.
Then here the question arises for "diamond problem" and how Java deal with that:-
In case of multiple inheritance of implementation java compiler gives compilation error and asks the user to fix it by specifying the interface name. Example here:-
interface A {
void method();
}
interface B extends A {
@Override
default void method() {
System.out.println("B");
}
}
interface C extends A {
@Override
default void method() {
System.out.println("C");
}
}
interface D extends B, C {
}
So here we will get error as:- interface D inherits unrelated defaults for method() from types B and C interface D extends B, C
You can fix it like:-
interface D extends B, C {
@Override
default void method() {
B.super.method();
}
}
In Conclusion we can say that java doesn't support multiple inheritance of state but it does support multiple inheritance of implementation and multiple inheritance of type.
Notice the repetition of Book
in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)
- it screams for a class type.
class Book {
int number;
String title;
String language;
int price;
}
Now you can simply have:
Book[] books = new Books[3];
If you want arrays, you can declare it as object array an insert Integer
and String
into it:
Object books[3][4]
Your working tree are the files that you are currently working on.
The git "index" is where you place files you want commit to the git repository.
The index is also known as cache, directory cache, current directory cache, staging area, staged files.
Before you "commit" (checkin) files to the git repository, you need to first place the files in the git "index".
The index is not the working directory: you can type a command such as git status
, and git will tell you what files in your working directory have been added to the git index (for example, by using the git add filename
command).
The index is not the git repository: files in the git index are files that git would commit to the git repository if you used the git commit command.
When server first starts the my.ini
may not be created where everyone has stated. I was able to find mine in C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.6
This location has the defaults for every setting.
# CLIENT SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
#
[client]
# pipe
# socket=0.0
port=4306 !!!!!!!!!!!!!!!!!!!Change this!!!!!!!!!!!!!!!!!
[mysql]
no-beep
default-character-set=utf8
while it might not matter now here is a function which generate a float between 2 values.
#include <math.h>
float func_Uniform(float left, float right) {
float randomNumber = sin(rand() * rand());
return left + (right - left) * fabs(randomNumber);
}
If you're running on an AWS instance that is running Amazon Linux OS, the magic command to fix this for me was
sudo yum install tkinter
If you want to determine your Linux build, try cat /etc/*release
To solve a similar problem, I'm using groupby
:
print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")
Whether that's appropriate will depend on what you want to do with the result, though (in my case, I just wanted the equivalent of COUNT DISTINCT
as shown).
Just write this query in your db phpmyadmin.
ALTER TABLE TableName ADD UNIQUE (FieldName)
Eg: ALTER TABLE user ADD UNIQUE (email)
OutOfMemoryException (on 32-bit machines) is just as often about Fragmentation as actual hard limits on memory - you'll find lots about this, but here's my first google hit briefly discussing it: http://blogs.msdn.com/b/joshwil/archive/2005/08/10/450202.aspx. (@Anthony Pegram is referring to the same problem in his comment above).
That said, there is one other possibility that comes to mind for your code above: As you're using the "IEnumerable" constructor to the List, you may not giving the object any hints as to the size of the collection you're passing to the List constructor. If the object you are passing is is not a collection (does not implement the ICollection
interface), then behind-the-scenes the List implementation is going to need to grow several (or many) times, each time leaving behind a too-small array that needs to be garbage collected. The garbage collector probably won't get to those discarded arrays fast enough, and you'll get your error.
The simplest fix for this would be to use the List(int capacity)
constructor to tell the framework what backing array size to allocate (even if you're estimating and just guessing "50000" for example), and then use the AddRange(IEnumerable collection)
method to actually populate your list.
So, simplest "Fix" if I'm right: replace
List<Vehicle> vList = new List<Vehicle>(selectedVehicles);
with
List<Vehicle> vList = new List<Vehicle>(50000);
vList.AddRange(selectedVehicles);
All the other comments and answers still apply in terms of overall design decisions - but this might be a quick fix.
Note (as @Alex commented below), this is only an issue if selectedVehicles
is not an ICollection.
try this:
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours()+':'+today.getMinutes()+':'+today.getSeconds();
console.log(date + ' '+ time);
_x000D_
I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1
Instead of changing the ticks, why not change the units instead? Make a separate array X
of x-values whose units are in nm. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel
to indicate the units (which should always be done anyways).
from pylab import *
# Generate random test data in your range
N = 200
epsilon = 10**(-9.0)
X = epsilon*(50*random(N) + 1)
Y = random(N)
# X2 now has the "units" of nanometers by scaling X
X2 = (1/epsilon) * X
subplot(121)
scatter(X,Y)
xlim(epsilon,50*epsilon)
xlabel("meters")
subplot(122)
scatter(X2,Y)
xlim(1, 50)
xlabel("nanometers")
show()
I've tried to activate env from Jenkins job (in bash) with
conda activate base
and it failed, so after many tries, this one worked for me (CentOS 7) :
source /opt/anaconda2/bin/activate base
This is an obviously lacking, but easily added fix for AngularJS. Just write a quick directive to set the model value from the input field.
<input name="card[description]" value="Visa-4242" ng-model="card.description" ng-initial>
Here's my version:
var app = angular.module('forms', []);
app.directive('ngInitial', function() {
return {
restrict: 'A',
controller: [
'$scope', '$element', '$attrs', '$parse', function($scope, $element, $attrs, $parse) {
var getter, setter, val;
val = $attrs.ngInitial || $attrs.value;
getter = $parse($attrs.ngModel);
setter = getter.assign;
setter($scope, val);
}
]
};
});
If one of the tables M
, S
, D
, or H
has more than one row for a given Id
(if just the Id
column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id
in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).
References:
Quick way to print something is:
select '** Place your mesage here' AS '** DEBUG:';
This will echo standard input to standard output:
import sys
line = sys.stdin.readline()
while line:
print line,
line = sys.stdin.readline()
1. for error: unescaped apostrophe in string
what I found is that AAPT2 tool points to wrong row in xml, sometimes. So you should correct whole strings.xml file
In Android Studio, in problem file use :
Edit->find->replace
Then write in first field \' (or \&,>,\<,\")
in second put '(or &,>,<,")
then replace each if needed.(or "reptlace all" in case with ')
Then in first field again put '(or &,>,<,")
and in second write \'
then replace each if needed.(or "replace all" in case with ')
2. for other problematic symbols
I use to comment each next half part +rebuild
until i won't find the wrong sign.
E.g. an escaped word "\update" unexpectedly drops such error :)
You can pass program arguments on the command line and get them in your Java app like this:
public static void main(String[] args) {
String pathToXml = args[0];
....
}
Alternatively you pass a system property by changing the command line to:
java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt
and your main class to:
public static void main(String[] args) {
String pathToXml = System.getProperty("path-to-xml");
....
}
Override timeout with SimpleClientHttpRequestFactory
//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
SimpleClientHttpRequestFactory clientHttpRequestFactory
= new SimpleClientHttpRequestFactory();
//Connect timeout
clientHttpRequestFactory.setConnectTimeout(10_000);
//Read timeout
clientHttpRequestFactory.setReadTimeout(10_000);
return clientHttpRequestFactory;
}
HTTPClient provides other useful features such as connection pool, idle connection management etc.
Read More : Spring RestTemplate + HttpClient configuration example
Override timeout with HttpComponentsClientHttpRequestFactory
//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
= new HttpComponentsClientHttpRequestFactory();
//Connect timeout
clientHttpRequestFactory.setConnectTimeout(10_000);
//Read timeout
clientHttpRequestFactory.setReadTimeout(10_000);
return clientHttpRequestFactory;
}
reference: Spring RestTemplate timeout configuration example
git log -n 1 [branch_name]
branch_name
(may be remote or local branch) is optional. Without branch_name
, it will show the latest commit on the current branch.
For example:
git log -n 1
git log -n 1 origin/master
git log -n 1 some_local_branch
git log -n 1 --pretty=format:"%H" #To get only hash value of commit
This also closely relates to:
if ("foo".equals(bar)) {
which is convenient if you don't want to deal with NPEs:
if (bar!=null && bar.equals("foo")) {
According to Extensible Messaging and Presence Protocol (Wikipedia), the standard TCP port for the server is 5222.
The client would presumably use the same ports as the messaging protocol, but can also use http (port 80) and https (port 443) for message delivery. These have the advantage of working for users behind firewalls, so your network admin should not need to get involved.
Say if you have
/**
*
*/
public KKSSocket(final KKSApp app, final String name) {
this.app = app;
this.name = name;
...
}
then a sub-class named KKSUDPSocket extending KKSSocket could have:
/**
* @param app
* @param path
* @param remoteAddr
*/
public KKSUDPSocket(KKSApp app, String path, KKSAddress remoteAddr) {
super(app, path, remoteAddr);
}
and
/**
* @param app
* @param path
*/
public KKSUDPSocket(KKSApp app, String path) {
super(app, path);
}
You simply pass the arguments up the constructor chain, like method calls to super classes, but using super(...) which references the super-class constructor and passes in the given args.
Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.
I would imagine you don't want your shell script to be in your web root, as it would be visible to anyone with web access to your server.
I would recommend moving the shell script to outside of the webroot
<?php
$tempFolder = '/tmp';
$webRootFolder = '/var/www';
$scriptName = 'myscript.sh';
$moveCommand = "mv $webRootFolder/$scriptName $tempFolder/$scriptName";
$output = shell_exec($moveCommand);
?>
In regards to the:
i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works
You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don't need to do this at all anyway.
Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it'll be fine.
ie:
sudo su apache (or www-data)
cd /var/www
sh ./myscript
Also... what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won't happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins - create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file
... voila
I would recommend to use this since I have the same issue which got fixed.
$('input:text').focus(
function(){
$(this).val('');
});
You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the same file though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)
To get the address of p do:
int **pp = &p;
and you can go on:
int ***ppp = &pp;
int ****pppp = &ppp;
...
or, only in C++11, you can do:
auto pp = std::addressof(p);
To print the address in C, most compilers support %p
, so you can simply do:
printf("addr: %p", pp);
otherwise you need to cast it (assuming a 32 bit platform)
printf("addr: 0x%u", (unsigned)pp);
In C++ you can do:
cout << "addr: " << pp;
If you want the text within the list items to be centred, try:
ul#menu-utility-navigation {
width: 100%;
}
ul#menu-utility-navigation li {
text-align: center;
}
Add-ons:If you want for eg: /users as application base for router and /public as base for assets use
$ ng build -prod --base-href /users --deploy-url /public
Most of the answers are/were valid. The new JAVA API modification for Date handling made sure that some earlier ambiguity in java date handling is reduced.
You will get a deprecated message for similar calls.
new Date() // deprecated
The above call had the developer to assume that a new Date object will give the Date object with current timestamp. This behavior is not consistent across other Java API classes.
The new way of doing this is using the Calendar Instance.
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()
Here too the naming convention is not perfect but this is much organised. For a person like me who has a hard time mugging up things but would never forget something if it sounds/appears logical, this is a good approach.
This is more synonymous to real life
One more way to do this is using Joda time API
new DateTime().toString("yyyy-MM-dd")
or the much obvious
new DateTime(Calendar.getInstance().getTime()).toString("yyyy-MM-dd")
both will return the same result.
The syntax and semantics are already well-defined by other excellent answers to this question. Because execution and performance are not detailed well, I will add my answer.
What is the functional difference between these 3?
I'd always considered atomic as a default quite curious. At the abstraction level we work at, using atomic properties for a class as a vehicle to achieve 100% thread-safety is a corner case. For truly correct multithreaded programs, intervention by the programmer is almost certainly a requirement. Meanwhile, performance characteristics and execution have not yet been detailed in depth. Having written some heavily multithreaded programs over the years, I had been declaring my properties as nonatomic
the entire time because atomic was not sensible for any purpose. During discussion of the details of atomic and nonatomic properties this question, I did some profiling encountered some curious results.
Execution
Ok. The first thing I would like to clear up is that the locking implementation is implementation-defined and abstracted. Louis uses @synchronized(self)
in his example -- I have seen this as a common source of confusion. The implementation does not actually use @synchronized(self)
; it uses object level spin locks. Louis's illustration is good for a high-level illustration using constructs we are all familiar with, but it's important to know it does not use @synchronized(self)
.
Another difference is that atomic properties will retain/release cycle your objects within the getter.
Performance
Here's the interesting part: Performance using atomic property accesses in uncontested (e.g. single-threaded) cases can be really very fast in some cases. In less than ideal cases, use of atomic accesses can cost more than 20 times the overhead of nonatomic
. While the Contested case using 7 threads was 44 times slower for the three-byte struct (2.2 GHz Core i7 Quad Core, x86_64). The three-byte struct is an example of a very slow property.
Interesting side note: User-defined accessors of the three-byte struct were 52 times faster than the synthesized atomic accessors; or 84% the speed of synthesized nonatomic accessors.
Objects in contested cases can also exceed 50 times.
Due to the number of optimizations and variations in implementations, it's quite difficult to measure real-world impacts in these contexts. You might often hear something like "Trust it, unless you profile and find it is a problem". Due to the abstraction level, it's actually quite difficult to measure actual impact. Gleaning actual costs from profiles can be very time consuming, and due to abstractions, quite inaccurate. As well, ARC vs MRC can make a big difference.
So let's step back, not focussing on the implementation of property accesses, we'll include the usual suspects like objc_msgSend
, and examine some real-world high-level results for many calls to a NSString
getter in uncontested cases (values in seconds):
As you have probably guessed, reference count activity/cycling is a significant contributor with atomics and under ARC. You would also see greater differences in contested cases.
Although I pay close attention to performance, I still say Semantics First!. Meanwhile, performance is a low priority for many projects. However, knowing execution details and costs of technologies you use certainly doesn't hurt. You should use the right technology for your needs, purposes, and abilities. Hopefully this will save you a few hours of comparisons, and help you make a better informed decision when designing your programs.
As of Angular2 RC5, myFormGroup.reset()
seems to do the trick.
I found an openoffice macro here that will invoke openoffice's compare documents function on two files. Unfortunately, openoffice's spreadsheet compare seems a little flaky; I just had the 'Reject All' button insert a superfluous column in my document.
You'll need a datasource
for working with JdbcTemplate
.
JdbcTemplate template = new JdbcTemplate(yourDataSource);
template.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection)
throws SQLException {
PreparedStatement statement = connection.prepareStatement(ourInsertQuery);
//statement.setLong(1, beginning); set parameters you need in your insert
return statement;
}
});
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBar.barTintColor = [UIColor blueColor];
}
In Xcode 6+ and iOS8+ you can do the simple steps below
Open terminal and paste the commands below:
cd desktop
xcrun simctl install booted xyz.app
For versions below iOS 8, do the following simple steps.
Note: You'll want to make sure that your app is built for all architectures, the Simulator is x386
in the Build Settings and Build Active Architecture Only
set to No
.
There is a very simple way to do this
function SharedPrivate(){
var private = "secret";
this.constructor.prototype.getP = function(){return private}
this.constructor.prototype.setP = function(v){ private = v;}
}
var o1 = new SharedPrivate();
var o2 = new SharedPrivate();
console.log(o1.getP()); // secret
console.log(o2.getP()); // secret
o1.setP("Pentax Full Frame K1 is on sale..!");
console.log(o1.getP()); // Pentax Full Frame K1 is on sale..!
console.log(o2.getP()); // Pentax Full Frame K1 is on sale..!
o2.setP("And it's only for $1,795._");
console.log(o1.getP()); // And it's only for $1,795._
JavaScript prototypes are golden.
System.Windows.Forms.MessageBox.Show("My message here");
Make sure the System.Windows.Forms
assembly is referenced your project.
Use the Integer
class' static toString()
method.
int sdRate=5;
text_Rate.setText(Integer.toString(sdRate));
There are a couple of mysql functions you need to look into.
mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false
value. Like the below:
while ($row = mysql_fetch_array($query)){
print_r $row;
}
Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..)
to get the row in an associative array.
Links:
In your case,
$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
die("BAD!");
}
if (mysql_num_rows($result)==1){
$row = mysql_fetch_array($result);
echo "user Id: " . $row['userid'];
}
else{
echo "not found!";
}
https://dev.mysql.com/doc/refman/8.0/en/alter-table.html
You can also set a default value for the column just add the DEFAULT keyword followed by the value.
ALTER TABLE [table_name] MODIFY [column_name] [NEW DATA TYPE] DEFAULT [VALUE];
This is also working for MariaDB (tested version 10.2)
It answers a little more than the OP is expecting... But I hope it could help some one at least.
If you want to execute a ICommand
whenever the SelectedItem
changed, you can bind a command on an event and the use of a property SelectedItem
in the ViewModel
isn't needed anymore.
To do so:
1- Add reference to System.Windows.Interactivity
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
2- Bind the command to the event SelectedItemChanged
<TreeView x:Name="myTreeView" Margin="1"
ItemsSource="{Binding Directories}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedItemChanged">
<i:InvokeCommandAction Command="{Binding SomeCommand}"
CommandParameter="
{Binding ElementName=myTreeView
,Path=SelectedItem}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TreeView.ItemTemplate>
<!-- ... -->
</TreeView.ItemTemplate>
</TreeView>
<?php foreach($have_comments as $key => $page_comment): ?>
<?php echo $page_comment;?>
<?php if($key+1<count($have_comments)): ?>
<?php echo ', '; ?>
<?php endif;?>
<?php endforeach;?>
This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End
and End Sub
are not the same. They don't perform the same task.
End
puts a stop to ALL code execution and you should almost always use Exit Sub
(or Exit Function
, respectively).
End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)
See also the MSDN dox for the End Statement
When executed, the
End
statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use theStop
statement instead. You can then resume execution while preserving the value of those variables.Note The
End
statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.
Nor is End Sub
and Exit Sub
the same. End Sub
can't be called in the same way Exit Sub
can be, because the compiler doesn't allow it.
This again means you have to Exit Sub
, which is a perfectly legal operation:
Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.
Additionally, and once you get the feel for how procedures work, obviously, End Sub
does not clear any global variables. But it does clear local (Dim'd) variables:
End Sub
Terminates the definition of this procedure.
If you don't want to go down the VBA path, there is this trick from a previous question.
Excel 2010: how to use autocomplete in validation list
It does add some annoying bulk to the top of your sheets, and potential maintenance (should you need more options, adding names of people from a staff list, new projects etc.) but works all the same.
Yes, but note: since the attribute selector (of course) targets the element's attribute, not the DOM node's value property (elem.value), it will not update while the form field is being updated.
Otherwise (with some trickery) I think it could have been used to make a CSS-only substitute for the "placeholder" attribute/functionality. Maybe that's what the OP was after? :)
SELECT OrderNo, shoppername, amountPayed, city, item, count(*) as cnt
FROM dbo.sales
GROUP BY OrderNo, shoppername, amountPayed, city, item
HAVING COUNT(*) > 1
My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:
This is what worked for me:
1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine.
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines.
5.) `git clone my_project`
6.) `vagrant up`
I had a few problems with VB Guest additions.
I fixed them with this solution.
i think you should do:
var myInterval
on.onclick = function() {
myInterval=setInterval(fontChange, 500);
};
off.onclick = function() {
clearInterval(myInterval);
};
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
The question reads "array of array" but I think most people probably come here just wanting to know how to save an array to UserDefaults
. For those people I will add a few common examples.
Save array
let array = ["horse", "cow", "camel", "sheep", "goat"]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")
Retrieve array
let defaults = UserDefaults.standard
let myarray = defaults.stringArray(forKey: "SavedStringArray") ?? [String]()
Save array
let array = [15, 33, 36, 723, 77, 4]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedIntArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedIntArray") as? [Int] ?? [Int]()
Save array
let array = [true, true, false, true, false]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedBoolArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedBoolArray") as? [Bool] ?? [Bool]()
Save array
let array = [Date(), Date(), Date(), Date()]
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedDateArray")
Retrieve array
let defaults = UserDefaults.standard
let array = defaults.array(forKey: "SavedDateArray") as? [Date] ?? [Date]()
Custom objects (and consequently arrays of objects) take a little more work to save to UserDefaults
. See the following links for how to do it.
??
) allows you to return the saved array or an empty array without crashing. It means that if the object returns nil, then the value following the ??
operator will be used instead.Int
, Bool
, and Date
. I also tested it with Double
. As far as I know, anything that you can save in a property list will work like this. You do not embed the images in the bundle. They are called through the browser. So its;
var imgSrc = './image/image1.jpg';
return <img src={imgSrc} />
There is a setting inside the PDF file that turns on the allow saving with data bit. However, it requires that you have a copy of Adobe Acrobat installed to change the bit.
The only other option is to print it to a PDF print driver which would save the data merged with the pdf file.
UPDATE: The relevant information from adobe is at: http://www.adobeforums.com/webx?13@@.3bbb313f/7
Take and store image in desired folder
//Global Variables
private static final int CAMERA_IMAGE_REQUEST = 101;
private String imageName;
Take picture function
public void captureImage() {
// Creating folders for Image
String imageFolderPath = Environment.getExternalStorageDirectory().toString()
+ "/AutoFare";
File imagesFolder = new File(imageFolderPath);
imagesFolder.mkdirs();
// Generating file name
imageName = new Date().toString() + ".png";
// Creating image here
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imageFolderPath, imageName)));
startActivityForResult(takePictureIntent,
CAMERA_IMAGE_REQUEST);
}
Broadcast new image added otherwise pic will not be visible in image gallery
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_IMAGE_REQUEST) {
Toast.makeText(getActivity(), "Success",
Toast.LENGTH_SHORT).show();
//Scan new image added
MediaScannerConnection.scanFile(getActivity(), new String[]{new File(Environment.getExternalStorageDirectory()
+ "/AutoFare/" + imageName).getPath()}, new String[]{"image/png"}, null);
// Work in few phones
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(Environment.getExternalStorageDirectory()
+ "/AutoFare/" + imageName)));
} else {
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(Environment.getExternalStorageDirectory()
+ "/AutoFare/" + imageName)));
}
} else {
Toast.makeText(getActivity(), "Take Picture Failed or canceled",
Toast.LENGTH_SHORT).show();
}
}
Permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Try git diff origin/master..master
(assuming that origin/master
is your upstream). Unlike git push --dry-run
, this still works even if you don't have write permission to the upstream.
I have created a snippet - inspired by the actual View source - that reliably detects long clicks/presses with a custom delay. But it's in Kotlin:
val LONG_PRESS_DELAY = 500
val handler = Handler()
var boundaries: Rect? = null
var onTap = Runnable {
handler.postDelayed(onLongPress, LONG_PRESS_DELAY - ViewConfiguration.getTapTimeout().toLong())
}
var onLongPress = Runnable {
// Long Press
}
override fun onTouch(view: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
boundaries = Rect(view.left, view.top, view.right, view.bottom)
handler.postDelayed(onTap, ViewConfiguration.getTapTimeout().toLong())
}
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
handler.removeCallbacks(onLongPress)
handler.removeCallbacks(onTap)
}
MotionEvent.ACTION_MOVE -> {
if (!boundaries!!.contains(view.left + event.x.toInt(), view.top + event.y.toInt())) {
handler.removeCallbacks(onLongPress)
handler.removeCallbacks(onTap)
}
}
}
return true
}
Html
$('#save').click(function(event) {
var jenis = $('#jenis').val();
var model = $('#model').val();
var harga = $('#harga').val();
var json = { "jenis" : jenis, "model" : model, "harga": harga};
$.ajax({
url: 'phone/save',
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){
alert(data);
}
});
event.preventDefault();
});
Controller
@Controller
@RequestMapping(value="/phone")
public class phoneController {
phoneDao pd=new phoneDao();
@RequestMapping(value="/save",method=RequestMethod.POST)
public @ResponseBody
int save(@RequestBody Smartphones phone)
{
return pd.save(phone);
}
Dao
public Integer save(Smartphones i) {
int id = 0;
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction trans=session.beginTransaction();
try {
session.save(i);
id=i.getId();
trans.commit();
}
catch(HibernateException he){}
return id;
}
In my case, I copied my class from somewhere else and didn't notice right away that it was an abstract
class. You can't inflate abstract classes.
Try making the bottom margin 100%.
margin-bottom: 100%;
Below is a snack bar component, when I give the snackbar variable directly into v-model like this if will work but in the console, it will give an error as
Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value.
<template>
<v-snackbar v-model="snackbar">
{{ text }}
</v-snackbar>
</template>
<script>
export default {
name: "loader",
props: {
snackbar: {type: Boolean, required: true},
text: {type: String, required: false, default: ""},
},
}
</script>
Correct Way to get rid of this mutation error is use watcher
<template>
<v-snackbar v-model="snackbarData">
{{ text }}
</v-snackbar>
</template>
<script>
/* eslint-disable */
export default {
name: "loader",
data: () => ({
snackbarData:false,
}),
props: {
snackbar: {type: Boolean, required: true},
text: {type: String, required: false, default: ""},
},
watch: {
snackbar: function(newVal, oldVal) {
this.snackbarData=!this.snackbarDatanewVal;
}
}
}
</script>
So in the main component where you will load this snack bar you can just do this code
<loader :snackbar="snackbarFlag" :text="snackText"></loader>
This Worked for me
If you're open to use third party libraries,'Angular Filters' with a nice collection of filters may be useful:
https://github.com/a8m/angular-filter#filterby
collection | filterBy: [prop, nested.prop, etc..]: search
Another option is to use the TimeUtils
utility method:
TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
}
is not called every time it is called only when app is in forground
there is one override method this method is called every time , no matter what app is in foreground or in background or killed but this method is available with this firebase api version
this is the version u have to import from gradle
compile 'com.google.firebase:firebase-messaging:10.2.1'
this is the method
@Override
public void handleIntent(Intent intent) {
super.handleIntent(intent);
// you can get ur data here
//intent.getExtras().get("your_data_key")
}
with previous firebase api this method was not there so in that case fire base handle itself when app is in background .... now u have this method what ever u want to do ... u can do it here in this method .....
if you are using previous version than default activity will start in that case u can get data same way
if(getIntent().getExtras() != null && getIntent().getExtras().get("your_data_key") != null) {
String strNotificaiton = getIntent().getExtras().get("your_data_key").toString();
// do what ever u want .... }
generally this is the structure from server we get in notification
{
"notification": {
"body": "Cool offers. Get them before expiring!",
"title": "Flat 80% discount",
"icon": "appicon",
"click_action": "activity name" //optional if required.....
},
"data": {
"product_id": 11,
"product_details": "details.....",
"other_info": "......."
}
}
it's up to u how u want to give that data key or u want give notification anything u can give ....... what ever u will give here with same key u will get that data .........
there are few cases if u r not sending click action in that case when u will click on notification default activity will open , but if u want to open your specific activity when app is in background u can call your activity from this on handleIntent method because this is called every time
I have to add an important difference between using node's build in cluster mode VS a process manager like PM2's cluster mode.
PM2 allows zero down time reloads when you are running.
pm2 start app.js -i 2 --wait-ready
In your codes add the following
process.send('ready');
When you call
pm2 reload app
after code updates, PM2 will reload the first instance of the app, wait for the 'ready' call, then it move on to reloads the next instance, ensuring you always have an app active to respond to requests.
While if you use nodejs' cluster, there will be down time when you restart and waiting for server to be ready.
I want to add my 2 cent experience that might be helpful for many of you.
If you declare a function inside a loop (for, foreach, while), you will face this error message.
By default, cin
reads from the input discarding any spaces. So, all you have to do is to use a do while
loop to read the input more than one time:
do {
cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
cin >> num;
// reset your variables
// your function stuff (calculations)
}
while (true); // or some condition
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
I also found a tool called TCP/IP Test Server [Edit: no longer available from the original developer, but still available via Brothersoft] which seems to do what I need too. But I didn't try it because it is not listed on big freeware-sites (like CNET...) and no source code is published so that it won't reassure a paranoid sysadmin.
I've just solved a problem related to this which may help other people.
Initially when loading up MSSMSE it had the server as PC_NAME\SQLEXPRESS
and when I tried to connect it gave me Error: 26 - Error Locating Server/Instance Specified
, so I went into SQL Server Configuration Manager to check if my SQL Server Browser
and SQL Server
services were running and set to automatic, only to find that instead of saying SQL Server (SQLEXPRESS)
it says SQL Server(MSSQLSERVER)
.
I then tried connecting to PC-NAME\MSSQLSERVER
and this time got SQL Network Interfaces, error: 25 - Connection string is not valid) (MicrosoftSQL Server, Error: 87) The parameter is incorrect
so I googled this error and found that somebody had suggested that instead of using PC-NAME\MSSQLSERVER
just use PC-NAME
as the Server Name at the server connection interface, and this seems to work.
There's a link here http://learningsqlserver.wordpress.com/2011/01/21/what-version-of-sql-server-do-i-have/ which explains that MSSQLSERVER is the default instance and can be connected to by using just your hostname.
I think this may have arisen because I've had SQL Server 2008 installed at some point in the past.
Here's a really nice one-liner to print all the Gems along with their version, homepage, and description:
Gem::Specification.sort{|a,b| a.name <=> b.name}.map {|a| puts "#{a.name} (#{a.version})"; puts "-" * 50; puts a.homepage; puts a.description; puts "\n\n"};nil
truncate removes all the rows, but not the table itself, it is essentially equivalent to deleting with no where clause, but usually faster.
Try this one if you want to pick only one option value.
$result = mysql_query("SELECT option_value FROM wp_10_options WHERE option_name='homepage'");
$row = mysql_fetch_array($result);
echo $row['option_value'];
You can use Url Parameters from the official documentation.
Example: this.httpClient.get(this.API, { params: new HttpParams().set('noCover', noCover) })
You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts
and the second is named ProductsOverTenDollars
.
WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
SELECT
CategoryID,
CategoryName,
(SELECT COUNT(1) FROM Products p
WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
FROM Categories c
),
ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
SELECT
ProductID,
CategoryID,
ProductName,
UnitPrice
FROM Products p
WHERE UnitPrice > 10.0
)
SELECT c.CategoryName, c.NumberOfProducts,
p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
INNER JOIN CategoryAndNumberOfProducts c ON
p.CategoryID = c.CategoryID
ORDER BY ProductName
Try GetElementsByTagName method of XMLDocument class to read specific data or LoadXml method to read all data to xml document.
You open the file in text mode.
More specifically:
ifile = open('sample.csv', "rt", encoding=<theencodingofthefile>)
Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.
In a SQL CASE clause, the first successfully matched condition is applied and any subsequent matching conditions are ignored.
Don't use while True and break statements. It's bad programming.
Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.
The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.
Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.
Solutions with changing position property are not always possible (it can destroy layout) therefore I suggest this:
HTML:
<a id="top">Anchor</a>
CSS:
#top {
margin-top: -250px;
padding-top: 250px;
}
Use this:
<a id="top"> </a>
to minimize overlapping, and set font-size to 1px. Empty anchor will not work in some browsers.
For those who do not have 4.5, Here is my library function that reads json. It requires a project reference to System.Web.Extensions
.
using System.Web.Script.Serialization;
public object DeserializeJson<T>(string Json)
{
JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
return JavaScriptSerializer.Deserialize<T>(Json);
}
Usually, json is written out based on a contract. That contract can and usually will be codified in a class (T
). Sometimes you can take a word from the json and search the object browser to find that type.
Example usage:
Given the json
{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}
You could parse it into a RadComboBoxClientState
object like this:
string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;
I solved, thanks. In case anyone's interested, bouncycastle did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:
var bytesToDecrypt = Convert.FromBase64String("la0Cz.....D43g=="); // string to decrypt, base64 encoded
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(@"c:\myprivatekey.pem")) // file containing RSA PKCS1 private key
keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject();
var decryptEngine = new Pkcs1Encoding(new RsaEngine());
decryptEngine.Init(false, keyPair.Private);
var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));
Simple:
st = "abcdefghij"
st = st[:-1]
There is also another way that shows how it is done with steps:
list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
This is also a way with user input:
list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)
To make it take away the last word in a list:
list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)
You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:
https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899
In this example, question 1, "Name", has an ID of 726721210
, while question 2, "Birthday" is 787184751
. Questions 3 and 4 are blank.
You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:
function buildUrls() {
var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1"); // Email, Name, Birthday
var data = ss.getDataRange().getValues();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
var url = template.replace('##Name##',escape(data[i][1]))
.replace('##Birthday##',data[i][2].yyyymmdd()); // see yyyymmdd below
Logger.log(url); // You could do something more useful here.
}
};
This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.
Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.
Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0]
is "Name", [1]
is "Birthday", and so on.
We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.
(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)
/**
* Use Form API to generate pre-filled form URLs
*/
function betterBuildUrls() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Sheet1");
var data = ss.getDataRange().getValues(); // Data for pre-fill
var formUrl = ss.getFormUrl(); // Use form attached to sheet
var form = FormApp.openByUrl(formUrl);
var items = form.getItems();
// Skip headers, then build URLs for each row in Sheet1.
for (var i = 1; i < data.length; i++ ) {
// Create a form response object, and prefill it
var formResponse = form.createResponse();
// Prefill Name
var formItem = items[0].asTextItem();
var response = formItem.createResponse(data[i][1]);
formResponse.withItemResponse(response);
// Prefill Birthday
formItem = items[1].asDateItem();
response = formItem.createResponse(data[i][2]);
formResponse.withItemResponse(response);
// Get prefilled form URL
var url = formResponse.toPrefilledUrl();
Logger.log(url); // You could do something more useful here.
}
};
Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd
. This helper function extends the Date object with a new method to handle the conversion.
When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975
you could use 5/9/1975
.)
// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
A variation of https://stackoverflow.com/a/12430764/589165 is
> nchar(gsub("[^a]", "", q.data$string))
[1] 2 1 0
I finally found out how to do this! Basically you need to run adb shell
first and then while you're in the shell run su
, which will switch the shell to run as root!
$: adb shell
$: su
The one problem I still have is that sqlite3 is not installed so the command is not recognized.
SQL Server allows the following (be careful to use single quotes instead of double)
UPDATE User
SET UserId = 12345
, Name = 'J Doe'
, Location = 'USA'
, Bio='my bio
spans
multiple
lines!'
WHERE UserId = 12345
As of 30Jul, 2018 to fix the above issue, one can configure the java version used within maven to any up to JDK/11 and make use of the maven-compiler-plugin:3.8.0
to specify a release of either 9,10,11 without any explicit dependencies.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<release>11</release> <!--or <release>10</release>-->
</configuration>
</plugin>
Note:- The default value for source/target has been lifted from 1.5 to 1.6 with this version. -- release notes.
Edit [30.12.2018]
In fact, you can make use of the same version of maven-compiler-plugin
while compiling the code against JDK/12 as well.
More details and a sample configuration in how to Compile and execute a JDK preview feature with Maven.
As to me, i need to caffe to my python path. I can add it's path to the file
/home/xy/.bashrc
by add
export PYTHONPATH=/home/xy/caffe-master/python:$PYTHONPATH
.
to my /home/xy/.bashrc
file.
But when I use pycharm, the path is still not in.
So I can add path to PYTHONPATH
variable, by run -> edit Configuration.
...
WHERE ...
AND (@Location is null OR (Location like '%' + @Location + '%'))
AND (@Date is null OR (Date = @Date))
This way it is more obvious the parameter is not used when null.
Try with this:
public static boolean userNameValidation(String name){
return name.matches("(?i)(^[a-z])((?![? .,'-]$)[ .]?[a-z]){3,24}$");
}
theView.post(new Runnable() {
String str;
@Override
public void run() {
par.Log(str);
}
public Runnable init(String pstr) {
this.str=pstr;
return(this);
}
}.init(str));
Create init function that returns object itself and initialize parameters with it.
the boolean value of an empty QuerySet is also False, so you could also just do...
...
if not user_object:
do insert or whatever etc.
EDIT: If all your keys are strings, then before continuing to read this answer, please see Jack O'Connor's significantly simpler (and faster) solution (which also works for hashing nested dictionaries).
Although an answer has been accepted, the title of the question is "Hashing a python dictionary", and the answer is incomplete as regards that title. (As regards the body of the question, the answer is complete.)
Nested Dictionaries
If one searches Stack Overflow for how to hash a dictionary, one might stumble upon this aptly titled question, and leave unsatisfied if one is attempting to hash multiply nested dictionaries. The answer above won't work in this case, and you'll have to implement some sort of recursive mechanism to retrieve the hash.
Here is one such mechanism:
import copy
def make_hash(o):
"""
Makes a hash from a dictionary, list, tuple or set to any level, that contains
only other hashable types (including any lists, tuples, sets, and
dictionaries).
"""
if isinstance(o, (set, tuple, list)):
return tuple([make_hash(e) for e in o])
elif not isinstance(o, dict):
return hash(o)
new_o = copy.deepcopy(o)
for k, v in new_o.items():
new_o[k] = make_hash(v)
return hash(tuple(frozenset(sorted(new_o.items()))))
Bonus: Hashing Objects and Classes
The hash()
function works great when you hash classes or instances. However, here is one issue I found with hash, as regards objects:
class Foo(object): pass
foo = Foo()
print (hash(foo)) # 1209812346789
foo.a = 1
print (hash(foo)) # 1209812346789
The hash is the same, even after I've altered foo. This is because the identity of foo hasn't changed, so the hash is the same. If you want foo to hash differently depending on its current definition, the solution is to hash off whatever is actually changing. In this case, the __dict__
attribute:
class Foo(object): pass
foo = Foo()
print (make_hash(foo.__dict__)) # 1209812346789
foo.a = 1
print (make_hash(foo.__dict__)) # -78956430974785
Alas, when you attempt to do the same thing with the class itself:
print (make_hash(Foo.__dict__)) # TypeError: unhashable type: 'dict_proxy'
The class __dict__
property is not a normal dictionary:
print (type(Foo.__dict__)) # type <'dict_proxy'>
Here is a similar mechanism as previous that will handle classes appropriately:
import copy
DictProxyType = type(object.__dict__)
def make_hash(o):
"""
Makes a hash from a dictionary, list, tuple or set to any level, that
contains only other hashable types (including any lists, tuples, sets, and
dictionaries). In the case where other kinds of objects (like classes) need
to be hashed, pass in a collection of object attributes that are pertinent.
For example, a class can be hashed in this fashion:
make_hash([cls.__dict__, cls.__name__])
A function can be hashed like so:
make_hash([fn.__dict__, fn.__code__])
"""
if type(o) == DictProxyType:
o2 = {}
for k, v in o.items():
if not k.startswith("__"):
o2[k] = v
o = o2
if isinstance(o, (set, tuple, list)):
return tuple([make_hash(e) for e in o])
elif not isinstance(o, dict):
return hash(o)
new_o = copy.deepcopy(o)
for k, v in new_o.items():
new_o[k] = make_hash(v)
return hash(tuple(frozenset(sorted(new_o.items()))))
You can use this to return a hash tuple of however many elements you'd like:
# -7666086133114527897
print (make_hash(func.__code__))
# (-7666086133114527897, 3527539)
print (make_hash([func.__code__, func.__dict__]))
# (-7666086133114527897, 3527539, -509551383349783210)
print (make_hash([func.__code__, func.__dict__, func.__name__]))
NOTE: all of the above code assumes Python 3.x. Did not test in earlier versions, although I assume make_hash()
will work in, say, 2.7.2. As far as making the examples work, I do know that
func.__code__
should be replaced with
func.func_code
Also check SELINUX (/etc/selinux):
# getenforce
turn it off:
# setenforce 0
I'll give you the query which you can run on kibana.
GET /_cat/indices?v
and the CURL version will be
CURL -XGET http://localhost:9200/_cat/indices?v
I don't know why, but if you use
(...)Formula = "=SUM(D2,E2)"
(',' instead of ';'), it works.
If you step through your sub in the VB script editor (F8), you can add Range("F2").Formula
to the watch window and see what the formular looks like from a VB point of view. It seems that the formular shown in Excel itself is sometimes different from the formular that VB sees...
@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decor = getWindow().getDecorView();
if (shouldChangeStatusBarTintToDark) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
} else {
// We want to change tint color to white again.
// You can also record the flags in advance so that you can turn UI back completely if
// you have set other flags before, such as translucent or full screen.
decor.setSystemUiVisibility(0);
}
}
Per the jQuery documentation, try this:
$('input[inputName\\[\\]=someValue]')
[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:
$('input[name="inputName[]"][value="someValue"]')
see http://api.jquery.com/show/
With no parameters, the .show() method is the simplest way to display an element:
$('.target').show();
The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling .css('display', 'block'), except that the display property is restored to whatever it was initially. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline.
You can also disable a specific rule/rules (rather than all) by specifying them in the enable (open) and disable (close) blocks:
/* eslint-disable no-alert, no-console */
alert('foo');
console.log('bar');
/* eslint-enable no-alert */
via @goofballMagic's link above: http://eslint.org/docs/user-guide/configuring.html#configuring-rules
Fitting a moving average to your data would smooth out the noise, see this this answer for how to do that.
If you'd like to use LOWESS to fit your data (it's similar to a moving average but more sophisticated), you can do that using the statsmodels library:
import numpy as np
import pylab as plt
import statsmodels.api as sm
x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.2
lowess = sm.nonparametric.lowess(y, x, frac=0.1)
plt.plot(x, y, '+')
plt.plot(lowess[:, 0], lowess[:, 1])
plt.show()
Finally, if you know the functional form of your signal, you could fit a curve to your data, which would probably be the best thing to do.
There is something wrong in the accepted answer.
int input = Integer.parseInt(dest.toString() + source.toString());
If I move cursor into middle of text, then type something, then the above statement will produce wrong result. For example, type "12" first, then type "0" between 1 and 2, then the statement mentioned above will produce "120" instead of 102. I modified this statement to statements below:
String destString = dest.toString();
String inputString = destString.substring(0, dstart) + source.toString() + destString.substring(dstart);
int input = Integer.parseInt(inputString);
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
def is_type(df, baseType):
import numpy as np
import pandas as pd
test = [issubclass(np.dtype(d).type, baseType) for d in df.dtypes]
return pd.DataFrame(data = test, index = df.columns, columns = ["test"])
def is_float(df):
import numpy as np
return is_type(df, np.float)
def is_number(df):
import numpy as np
return is_type(df, np.number)
def is_integer(df):
import numpy as np
return is_type(df, np.integer)
Not completely clear what you mean. Perhaps:
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var params = {};
params['pageNo'] = $(this).text();
params['sortBy'] = $("#sortBy").val();
$("#results").load( "jquery-routing.php", params );
return false;
});
});
</script>
in my opinion the easiest way would be somthing like this:
<?php>
echo '<a href="link.php?submit='.$value.'">Submit</a>';
</?>
within the "link.php" you can request the value like this:
$_REQUEST['submit']
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g
and you will be able to use it in terminal like http-server C:\location\to\app.
Kirill Fuchs
If you use Ramda you can use its omit and clone functions to make a deep clone of your object and omit the unnecessary fields.
var object = {a: 1, b: 2, c: 3, y:25, z:26};
R.clone(R.omit(["z", "y"], object));
i have the same problem here VS2015 didn't recognize my js files changes, removing remotes from repository settings and then re-adding the remote URL path solved my problem.
This program has a functions for
Find Successor
class BNode{
int data;
BNode left, right;
public BNode(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
public class BST {
static BNode root;
public int add(int value){
BNode newNode, current;
newNode = new BNode(value);
if(root == null){
root = newNode;
current = root;
}
else{
current = root;
while(current.left != null || current.right != null){
if(newNode.data < current.data){
if(current.left != null)
current = current.left;
else
break;
}
else{
if(current.right != null)
current = current.right;
else
break;
}
}
if(newNode.data < current.data)
current.left = newNode;
else
current.right = newNode;
}
return value;
}
public void inorder(BNode root){
if (root != null) {
inorder(root.left);
System.out.println(root.data);
inorder(root.right);
}
}
public boolean find(int value){
boolean flag = false;
BNode current;
current = root;
while(current!= null){
if(current.data == value){
flag = true;
break;
}
else if(current.data > value)
current = current.left;
else
current = current.right;
}
System.out.println("Is "+value+" present in tree? : "+flag);
return flag;
}
public void successor(int value){
BNode current;
current = root;
if(find(value)){
while(current.data != value){
if(value < current.data && current.left != null){
System.out.println("Node is: "+current.data);
current = current.left;
}
else if(value > current.data && current.right != null){
System.out.println("Node is: "+current.data);
current = current.right;
}
}
}
else
System.out.println(value+" Element is not present in tree");
}
public static void main(String[] args) {
BST b = new BST();
b.add(50);
b.add(30);
b.add(20);
b.add(40);
b.add(70);
b.add(60);
b.add(80);
b.add(90);
b.inorder(root);
b.find(30);
b.find(90);
b.find(100);
b.find(50);
b.successor(90);
System.out.println();
b.successor(70);
}
}
This is an issue distinct to Chrome, but there are two paths you can take to fix it.
I noticed the error once I added this specific header to my PHP script.
header('Content-Type: application/json');
The error appears to be related to PHP sessions when sending response headers. So according to chromium bug report 424599, this was fixed and you can just update to a newer version of Chrome. But if for some reason you can't or don't want to update, the workaround would be to remove these response headers from your PHP script if possible (that's what I did because it wasn't required).
I'm currently using this function (based on other answers) in VB.NET:
Private Shared Function SplitLines(text As String) As String()
Return text.Split({Environment.NewLine, vbCrLf, vbLf}, StringSplitOptions.None)
End Function
It tries to split on the platform-local newline first, and then falls back to each possible newline.
I've only needed this inside one class so far. If that changes, I will probably make this Public
and move it to a utility class, and maybe even make it an extension method.
Here's how to join the lines back up, for good measure:
Private Shared Function JoinLines(lines As IEnumerable(Of String)) As String
Return String.Join(Environment.NewLine, lines)
End Function
There is a contains
method for lists, so you should be able to do:
Arrays.asList(yourArray).contains(yourObject);
Warning: this might not do what you (or I) expect, see Tom's comment below.
you can also print the data onto your HTML/JSP document. like:-
<!DOCTYPE html>
<html>
<head>
<title>Jsp Sample</title>
<%@page import="java.sql.*;"%>
</head>
<body bgcolor=yellow>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection)DriverManager.getConnection(
"jdbc:mysql://localhost:3306/forum","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student;");
%><table border=1 align=center style="text-align:center">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>SKILL</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<%while(rs.next())
{
%>
<tr>
<td><%=rs.getString("id") %></td>
<td><%=rs.getString("name") %></td>
<td><%=rs.getString("skill") %></td>
<td><%=rs.getString("action") %></td>
</tr>
<%}%>
</tbody>
</table><br>
<%}
catch(Exception e){
out.print(e.getMessage());%><br><%
}
finally{
st.close();
con.close();
}
%>
</body>
</html>
<!--executeUpdate() mainupulation and executeQuery() for retriving-->
As explained in this thread on the cxf-user mailing list, rather than having the CXFServlet load its own spring context from user-webservice-servlet.xml
, you can just load the whole lot into the root context. Rename your existing user-webservice-servlet.xml
to some other name (e.g. user-webservice-beans.xml
) then change your contextConfigLocation
parameter to something like:
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/user-webservice-beans.xml
</param-value>
</context-param>
<servlet>
<servlet-name>user-webservice</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>user-webservice</servlet-name>
<url-pattern>/UserService/*</url-pattern>
</servlet-mapping>
As of September 2017,
1. Click on your project.
2. Select setting on the top most corner.
3. Scroll down the page and click on expand in front of advance setting.
4. Scroll down the page and click on the Remove Project button.
5. Type your project name in text box and click on confirm.
For 100% viewport height use:
overflow: auto;
max-height: 100vh;
you can check the type. s3 has a special application/x-directory
bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }
When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.
You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:
var color = $( this ).css( "background-color" );
var r = parseInt(color.match(/\d+/g)[0]);
var g = parseInt(color.match(/\d+/g)[1]);
var b = parseInt(color.match(/\d+/g)[2]);
git archive --format=tar --remote=<repository URL> HEAD | tar xf -
taken from here
Resources in Scala work exactly as they do in Java.
It is best to follow the Java best practices and put all resources in src/main/resources
and src/test/resources
.
Example folder structure:
testing_styles/
+-- build.sbt
+-- src
¦ +-- main
¦ +-- resources
¦ ¦ +-- readme.txt
To read resources the object Source provides the method fromResource.
import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines
To read resources you can use getClass.getResource and getClass.getResourceAsStream .
val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines
To avoid undebuggable Java NPEs, consider:
import scala.util.Try
import scala.io.Source
import java.io.FileNotFoundException
object Example {
def readResourceWithNiceError(resourcePath: String): Try[Iterator[String]] =
Try(Source.fromResource(resourcePath).getLines)
.recover(throw new FileNotFoundException(resourcePath))
}
Keep in mind that getResourceAsStream also works fine when the resources are part of a jar, getResource, which returns a URL which is often used to create a file can lead to problems there.
In production code I suggest to make sure that the source is closed again.
The method len() returns the number of elements in the list.
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
When we run above program, it produces the following result -
First list length : 3 Second list length : 2
Try This:
$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_URL, urlencode($url));
$response = curl_exec($ch);
curl_close($ch);
You can try using Scanner if you are using JDK5 or higher.
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
Or you can also use Guava
String data = Files.toString(new File("path.txt"), Charsets.UTF8);
I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3
into CSV and prompt you to download/open in Excel.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSON to CSV</title>
<script src="scripts/json.js" type="text/javascript"></script>
<script type="text/javascript">
var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }
DownloadJSON2CSV(json3.d);
function DownloadJSON2CSV(objArray)
{
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
line += array[i][index] + ',';
}
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
line.slice(0,line.Length-1);
str += line + '\r\n';
}
window.open( "data:text/csv;charset=utf-8," + escape(str))
}
</script>
</head>
<body>
<h1>This page does nothing....</h1>
</body>
</html>
Try this: really quick + worked for me:
ps: excuse image below for different language :)
Long ago, when all we had was sh
, Booleans where handled by relying on a convention of the test
program where test
returns a false exit status if run without any arguments.
This allows one to think of a variable that is unset as false and variable set to any value as true. Today, test
is a builtin to Bash and is commonly known by its one-character alias [
(or an executable to use in shells lacking it, as dolmen notes):
FLAG="up or <set>"
if [ "$FLAG" ] ; then
echo 'Is true'
else
echo 'Is false'
fi
# Unset FLAG
# also works
FLAG=
if [ "$FLAG" ] ; then
echo 'Continues true'
else
echo 'Turned false'
fi
Because of quoting conventions, script writers prefer to use the compound command [[
that mimics test
, but has a nicer syntax: variables with spaces do not need to be quoted; one can use &&
and ||
as logical operators with weird precedence, and there are no POSIX limitations on the number of terms.
For example, to determine if FLAG is set and COUNT is a number greater than 1:
FLAG="u p"
COUNT=3
if [[ $FLAG && $COUNT -gt '1' ]] ; then
echo 'Flag up, count bigger than 1'
else
echo 'Nope'
fi
This stuff can get confusing when spaces, zero length strings, and null variables are all needed and also when your script needs to work with several shells.
Or to make it more explicit than the other answer:
git pull
whoops?
git reset --keep HEAD@{1}
Versions of git older than 1.7.1 do not have --keep
. If you use such version, you could use --hard
- but that is a dangerous operation because it loses any local changes.
ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation)
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list, inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;
It is written here that "By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing."
As it seems that these new checkboxes appeared with Android 2.3, I understand that my previous versions of Android Studio (at least the 2.2) did sign with both signatures. So, to continue as I did before, I think that it is better to check both checkboxes.
EDIT March 31st, 2017 : submitted several apps with both signatures => no problem :)
To enforce non-www and https in a single request, you can use the following Rule in your htaccess :
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\. [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
This redirects http://www.example.com/ or https://www.example.com/ to ssl non-www https://example.com/ .
I am using R Temp Redirect flag for testing purpose and to avoid browser caching. If you want to make the redirect permanent , just change the R flag to R=301 .
Yes, there is. You can use the Arrays class from the java.util.* package. Then it's actually just one line of code.
List<String> list = Arrays.asList(array);
var myColumnDefs = new Array();
for (var i = 0; i < oFullResponse.results.length; i++) {
myColumnDefs.push({key:oFullResponse.results[i].label, sortable:true, resizeable:true});
}
There's a couple of other tricks that Postgres offers for string matching (if that happens to be your DB):
ILIKE, which is a case insensitive LIKE match:
select * from people where name ilike 'JOHN'
Matches:
And if you want to get really mad you can use regular expressions:
select * from people where name ~ 'John.*'
Matches:
This is an old answer with deprecated and hacky way of overcoming some specific content resolver pain points. Take it with some huge grains of salt and use the proper openInputStream API if at all possible.
You can use the Content Resolver to get a file://
path from the content://
URI:
String filePath = null;
Uri _uri = data.getData();
Log.d("","URI = "+ _uri);
if (_uri != null && "content".equals(_uri.getScheme())) {
Cursor cursor = this.getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();
} else {
filePath = _uri.getPath();
}
Log.d("","Chosen path = "+ filePath);
Visual Studio Code: Version: 1.53.2
If you are looking for the answer in 2021 (like I was), the answer is here on the Microsoft website but honestly hard to follow.
Go to Edit > Replace in Files
From there it is similar to the search funtionality for a single file.
I changed the name of a class I was using across files and this worked perfectly.
Note: If you cannot find the Replace in Files option, first click on the Search icon (magnifying glass) and then it will appear.
It's probably worth to try with neural networks if you are able to create some training data... but this needs many samples annotated by hand.
This worked for me On Windows 10,
xcopy /s {source drive..i.e. C:} {destination drive..i.e. D:} This will copy all the files and folders plus the folder contents.
For the latest Node.js
sudo apt-get install curl
curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
sudo apt-get install nodejs
node -v
npm -v
You can also plot to a png file using gnuplot (which is free):
terminal commands
gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'
note: you always need to give the right extension (.png here) at set output
Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:
plot '<Fromfile.csv>' with line lt -1 lw 2
More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html
apt-get install gnuplot
)brew install gnuplot
)Jackson has to know in what order to pass fields from a JSON object to the constructor. It is not possible to access parameter names in Java using reflection - that's why you have to repeat this information in annotations.
Not exactly sure why, but changing the inner CSS to
display: inline-block;
seems to work.
Using ES2015/ES6 spread operator
[...Array(10)].map((_, i) => i + 1)
console.log([...Array(10)].map((_, i) => i + 1))
_x000D_
I had similar issues on ubuntu 12.04. Installing Node.js fixed it.
Any Primitive data type like int,boolean, or float etc can't store the null(lateral),since java has provided Wrapper class for storing the same like int to Integer,boolean to Boolean.
Eg: Integer i=null;
Following will disable all the input but will not able it to btn class and also added class to overwrite disable css.
$('#EditForm :input').not('.btn').attr("disabled", true).addClass('disabledClass');
css class
.disabledClass{
background-color: rgb(235, 235, 228) !important;
}
This css solution worked for me:
input:active,
input:focus {
border: 1px solid #red
}
input:active,
input:focus {
padding: 2px solid #red /*for firefox and chrome*/
}
/* .ie is a class you would need to set at the html root level */
.ie input:active,
.ie input:focus {
padding: 3px solid #red /* IE needs 1px extra padding*/
}
I understand it is not necessary on FF and Chrome, but IE needs it. And there are circumstances when you need it.
An HttpOnly
cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly
attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly
.
Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly
by just XSS and still have access to the cookie via JS and thus make the HttpOnly
on your cookie completely useless.
Provide a module whose responsibility is to execute requests sequentially, while tracking the current index of each operation in an ordinal manner. Define the operation in a Command Pattern for flexibility.
execute
method to chain & track each operation. SequentialPromise returns a Promise-Chain from all operations performed.execute
method while passing in an ordinal list of options for each operation.Use SequentialPromise when ordinal behavior of Promise resolution is needed. SequentialPromise will track the index for which a Promise was rejected.
clear();
var http = {
get(url) {
var delay = Math.floor( Math.random() * 10 ), even = !(delay % 2);
var xhr = new Promise(exe);
console.log(`REQUEST`, url, delay);
xhr.then( (data) => console.log(`SUCCESS: `, data) ).catch( (data) => console.log(`FAILURE: `, data) );
function exe(resolve, reject) {
var action = { 'true': reject, 'false': resolve }[ even ];
setTimeout( () => action({ url, delay }), (1000 * delay) );
}
return xhr;
}
};
var SequentialPromise = new (function SequentialPromise() {
var PRIVATE = this;
return class SequentialPromise {
constructor(context, action) {
this.index = 0;
this.requests = [ ];
this.context = context;
this.action = action;
return this;
}
log() {}
execute(url, ...more) {
var { context, action, requests } = this;
var chain = context[action](url);
requests.push(chain);
chain.then( (data) => this.index += 1 );
if (more.length) return chain.then( () => this.execute(...more) );
return chain;
}
};
})();
var sequence = new SequentialPromise(http, 'get');
var urls = [
'url/name/space/0',
'url/name/space/1',
'url/name/space/2',
'url/name/space/3',
'url/name/space/4',
'url/name/space/5',
'url/name/space/6',
'url/name/space/7',
'url/name/space/8',
'url/name/space/9'
];
var chain = sequence.execute(...urls);
var promises = sequence.requests;
chain.catch( () => console.warn(`EXECUTION STOPPED at ${sequence.index} for ${urls[sequence.index]}`) );
// console.log('>', chain, promises);
I found myself in this situation when I tried to rebase a branch that was tracking a remote branch, and I was trying to rebase it on master. In this scenario if you try to rebase, you'll most likely find your branch diverged and it can create a mess that isn't for git nubees!
Let's say you are on branch my_remote_tracking_branch, which was branched from master
$ git status
# On branch my_remote_tracking_branch
nothing to commit (working directory clean)
And now you are trying to rebase from master as:
git rebase master
STOP NOW and save yourself some trouble! Instead, use merge as:
git merge master
Yes, you'll end up with extra commits on your branch. But unless you are up for "un-diverging" branches, this will be a much smoother workflow than rebasing. See this blog for a much more detailed explanation.
On the other hand, if your branch is only a local branch (i.e. not yet pushed to any remote) you should definitely do a rebase (and your branch will not diverge in this case).
Now if you are reading this because you already are in a "diverged" scenario due to such rebase, you can get back to the last commit from origin (i.e. in an un-diverged state) by using:
git reset --hard origin/my_remote_tracking_branch
Personally I use PDO, but I think that is mainly a question of preference.
PDO has some features that help agains SQL injection (prepared statements), but if you are careful with your SQL you can achieve that with mysqli, too.
Moving to another database is not so much a reason to use PDO. As long as you don't use "special SQL features", you can switch from one DB to another. However as soon as you use for example "SELECT ... LIMIT 1" you can't go to MS-SQL where it is "SELECT TOP 1 ...". So this is problematic anyway.
Add this to your css.
.highcharts-credits {
display: none !important;
}
This is in slight response to Joel's comment about making a slighly more optimized version. Instead of returning a random date directly, why not return a generator function which can be called repeatedly to create a random date.
Func<DateTime> RandomDayFunc()
{
DateTime start = new DateTime(1995, 1, 1);
Random gen = new Random();
int range = ((TimeSpan)(DateTime.Today - start)).Days;
return () => start.AddDays(gen.Next(range));
}
Another one line command I used is:
[ -e file ] && rm file
I created this simple example from different search results on the internet.
public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
//Create base address
string baseAddress = "net.pipe://localhost/MyService";
ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));
//Net named pipe
NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);
//MEX - Meta data exchange
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
serviceHost.Description.Behaviors.Add(behavior);
serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");
return serviceHost;
}
Using the above URI I can add a reference in my client to the web service.
Please make the following part of the Collectors API:
<K, V> Collector<? super Map.Entry<K, V>, ?, Map<K, V>> toMap() {
return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
Its more than just setting the connection to null. That may be what the documentation says, but that is not the truth for mysql. The connection will stay around for a bit longer (Ive heard 60s, but never tested it)
If you want to here the full explanation see this comment on the connections https://www.php.net/manual/en/pdo.connections.php#114822
To force the close the connection you have to do something like
$this->connection = new PDO();
$this->connection->query('KILL CONNECTION_ID()');
$this->connection = null;
like Jesse Jesse Glick and abguy said you can enumerate string into Boolean type:
Boolean.valueOf(string_variable)
or the opposite Boolean into string:
String.valueOf(boolean_variable)
in my case I had to to downstream Boolean parameter to another job. So for this you will need the use the class BooleanParameterValue :
build job: 'downstream_job_name', parameters:
[
[$class: 'BooleanParameterValue', name: 'parameter_name', value: false],
], wait: true
user@host> g++ hw.cpp
user@host> ./a.out
If you specifically have an array of arrays that doesn't go further than one level deep (a use case I find common) you can get away with array_merge
and the splat operator.
<?php
$notFlat = [[1,2],[3,4]];
$flat = array_merge(...$notFlat);
var_dump($flat);
Output:
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
The splat operator effectively changes the array of arrays to a list of arrays as arguments for array_merge
.
printf() doesn't directly support that. Instead you have to make your own function.
Something like:
while (n) {
if (n & 1)
printf("1");
else
printf("0");
n >>= 1;
}
printf("\n");
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
| | Struct | Class |
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
| Type | Value-type | Reference-type |
| Where | On stack / Inline in containing type | On Heap |
| Deallocation | Stack unwinds / containing type gets deallocated | Garbage Collected |
| Arrays | Inline, elements are the actual instances of the value type | Out of line, elements are just references to instances of the reference type residing on the heap |
| Aldel Cost | Cheap allocation-deallocation | Expensive allocation-deallocation |
| Memory usage | Boxed when cast to a reference type or one of the interfaces they implement, | No boxing-unboxing |
| | Unboxed when cast back to value type | |
| | (Negative impact because boxes are objects that are allocated on the heap and are garbage-collected) | |
| Assignments | Copy entire data | Copy the reference |
| Change to an instance | Does not affect any of its copies | Affect all references pointing to the instance |
| Mutability | Should be immutable | Mutable |
| Population | In some situations | Majority of types in a framework should be classes |
| Lifetime | Short-lived | Long-lived |
| Destructor | Cannot have | Can have |
| Inheritance | Only from an interface | Full support |
| Polymorphism | No | Yes |
| Sealed | Yes | When have sealed keyword |
| Constructor | Can not have explicit parameterless constructors | Any constructor |
| Null-assignments | When marked with nullable question mark | Yes (+ When marked with nullable question mark in C# 8+) |
| Abstract | No | When have abstract keyword |
| Member Access Modifiers| public, private, internal | public, protected, internal, protected internal, private protected |
+------------------------+------------------------------------------------------------------------------------------------------+---------------------------------------------------------------------------------------------------+
See the following methods:
~ : Changes the case of current character
guu : Change current line from upper to lower.
gUU : Change current LINE from lower to upper.
guw : Change to end of current WORD from upper to lower.
guaw : Change all of current WORD to lower.
gUw : Change to end of current WORD from lower to upper.
gUaw : Change all of current WORD to upper.
g~~ : Invert case to entire line
g~w : Invert case to current WORD
guG : Change to lowercase until the end of document.