Not mention so far and an update, there is a very well establish library for handling paths that are too long. AlphaFS is a .NET library providing more complete Win32 file system functionality to the .NET platform than the standard System.IO classes. The most notable deficiency of the standard .NET System.IO is the lack of support of advanced NTFS features, most notably extended length path support (eg. file/directory paths longer than 260 characters).
Simply :first
works for me, why isn't this mentioned yet?
For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.
$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
$('#new_post button').prop 'disabled', if @value == '' then true else false
return
The command Edit.ParameterInfo
(mapped to Ctrl+Shift+Space by default) will show the overload tooltip if it's invoked when the cursor is inside the parameter brackets of a method call.
The command Edit.QuickInfo
(mapped to Ctrl+KCtrl+I by default) will show the tooltip that you'd see if you moused over the cursor location.
Try... csv download.
<?php
mysql_connect('hostname', 'username', 'password');
mysql_select_db('dbname');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
$data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
echo $data; exit();
?>
import React from 'react';
import {sendFormData} from '../services/';
class Signup extends React.Component{
constructor(props){
super(props);
this.state = {
isDisabled:true
}
this.submitForm = this.submitForm.bind(this);
}
validateEmail(email){
const pattern = /[a-zA-Z0-9]+[\.]?([a-zA-Z0-9]+)?[\@][a-z]{3,9}[\.][a-z]{2,5}/g;
const result = pattern.test(email);
if(result===true){
this.setState({
emailError:false,
email:email
})
} else{
this.setState({
emailError:true
})
}
}
handleChange(e){
const target = e.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
if(e.target.name==='firstname'){
if(e.target.value==='' || e.target.value===null ){
this.setState({
firstnameError:true
})
} else {
this.setState({
firstnameError:false,
firstName:e.target.value
})
}
}
if(e.target.name==='lastname'){
if(e.target.value==='' || e.target.value===null){
this.setState({
lastnameError:true
})
} else {
this.setState({
lastnameError:false,
lastName:e.target.value
})
}
}
if(e.target.name==='email'){
this.validateEmail(e.target.value);
}
if(e.target.name==='password'){
if(e.target.value==='' || e.target.value===null){
this.setState({
passwordError:true
})
} else {
this.setState({
passwordError:false,
password:e.target.value
})
}
}
if(this.state.firstnameError===false && this.state.lastnameError===false &&
this.state.emailError===false && this.state.passwordError===false){
this.setState({
isDisabled:false
})
}
}
submitForm(e){
e.preventDefault();
const data = {
firstName: this.state.firstName,
lastName: this.state.lastName,
email: this.state.email,
password: this.state.password
}
sendFormData(data).then(res=>{
if(res.status===200){
alert(res.data);
this.props.history.push('/');
}else{
}
});
}
render(){
return(
<div className="container">
<div className="card card-login mx-auto mt-5">
<div className="card-header">Register here</div>
<div className="card-body">
<form id="signup-form">
<div className="form-group">
<div className="form-label-group">
<input type="text" id="firstname" name="firstname" className="form-control" placeholder="Enter firstname" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="firstname">firstname</label>
{this.state.firstnameError ? <span style={{color: "red"}}>Please Enter some value</span> : ''}
</div>
</div>
<div className="form-group">
<div className="form-label-group">
<input type="text" id="lastname" name="lastname" className="form-control" placeholder="Enter lastname" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="lastname">lastname</label>
{this.state.lastnameError ? <span style={{color: "red"}}>Please Enter some value</span> : ''}
</div>
</div>
<div className="form-group">
<div className="form-label-group">
<input type="email" id="email" name="email" className="form-control" placeholder="Enter your email" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="email">email</label>
{this.state.emailError ? <span style={{color: "red"}}>Please Enter valid email address</span> : ''}
</div>
</div>
<div className="form-group">
<div className="form-label-group">
<input type="password" id="password" name="password" className="form-control" placeholder="Password" onChange={(e)=>{this.handleChange(e)}} />
<label htmlFor="password">Password</label>
{this.state.passwordError ? <span style={{color: "red"}}>Please enter some value</span> : ''}
</div>
</div>
<button className="btn btn-primary btn-block" disabled={this.state.isDisabled} onClick={this.submitForm}>Signup</button>
</form>
</div>
</div>
</div>
);
}
}
export default Signup;
By all your powers combined I use this helper class for reading resources from any assembly and any namespace in a generic way.
public class ResourceReader
{
public static IEnumerable<string> FindEmbededResources<TAssembly>(Func<string, bool> predicate)
{
if (predicate == null) throw new ArgumentNullException(nameof(predicate));
return
GetEmbededResourceNames<TAssembly>()
.Where(predicate)
.Select(name => ReadEmbededResource(typeof(TAssembly), name))
.Where(x => !string.IsNullOrEmpty(x));
}
public static IEnumerable<string> GetEmbededResourceNames<TAssembly>()
{
var assembly = Assembly.GetAssembly(typeof(TAssembly));
return assembly.GetManifestResourceNames();
}
public static string ReadEmbededResource<TAssembly, TNamespace>(string name)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
return ReadEmbededResource(typeof(TAssembly), typeof(TNamespace), name);
}
public static string ReadEmbededResource(Type assemblyType, Type namespaceType, string name)
{
if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
if (namespaceType == null) throw new ArgumentNullException(nameof(namespaceType));
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
return ReadEmbededResource(assemblyType, $"{namespaceType.Namespace}.{name}");
}
public static string ReadEmbededResource(Type assemblyType, string name)
{
if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
var assembly = Assembly.GetAssembly(assemblyType);
using (var resourceStream = assembly.GetManifestResourceStream(name))
{
if (resourceStream == null) return null;
using (var streamReader = new StreamReader(resourceStream))
{
return streamReader.ReadToEnd();
}
}
}
}
Another option (especially if you're rolling you own class) is to use an int or a int64, and designate the lower four digits (or possibly even 2) as "right of the decimal point". So "on the edges" you'll need some "* 10000" on the way in and some "/ 10000" on the way out. This is the storage mechanism used by Microsoft's SQL Server, see http://msdn.microsoft.com/en-au/library/ms179882.aspx
The nicity of this is that all your summation can be done using (fast) integer arithmetic.
For those like me who are brand new to this, here is code with const and an actual way to compare the byte[]'s. I got all of this code from stackoverflow but defined consts so values could be changed and also
// 24 = 192 bits
private const int SaltByteSize = 24;
private const int HashByteSize = 24;
private const int HasingIterationsCount = 10101;
public static string HashPassword(string password)
{
// http://stackoverflow.com/questions/19957176/asp-net-identity-password-hashing
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, SaltByteSize, HasingIterationsCount))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(HashByteSize);
}
byte[] dst = new byte[(SaltByteSize + HashByteSize) + 1];
Buffer.BlockCopy(salt, 0, dst, 1, SaltByteSize);
Buffer.BlockCopy(buffer2, 0, dst, SaltByteSize + 1, HashByteSize);
return Convert.ToBase64String(dst);
}
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] _passwordHashBytes;
int _arrayLen = (SaltByteSize + HashByteSize) + 1;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != _arrayLen) || (src[0] != 0))
{
return false;
}
byte[] _currentSaltBytes = new byte[SaltByteSize];
Buffer.BlockCopy(src, 1, _currentSaltBytes, 0, SaltByteSize);
byte[] _currentHashBytes = new byte[HashByteSize];
Buffer.BlockCopy(src, SaltByteSize + 1, _currentHashBytes, 0, HashByteSize);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, _currentSaltBytes, HasingIterationsCount))
{
_passwordHashBytes = bytes.GetBytes(SaltByteSize);
}
return AreHashesEqual(_currentHashBytes, _passwordHashBytes);
}
private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
{
int _minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
var xor = firstHash.Length ^ secondHash.Length;
for (int i = 0; i < _minHashLength; i++)
xor |= firstHash[i] ^ secondHash[i];
return 0 == xor;
}
In in your custom ApplicationUserManager, you set the PasswordHasher property the name of the class which contains the above code.
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
The below code may help you.
protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
numberFormat.setGroupingUsed(true);
numberFormat.setMaximumFractionDigits(2);
numberFormat.setMinimumFractionDigits(2);
return numberFormat.format(input);
}
Or if "NOT EXISTS" are not implemented
SELECT *
FROM B
WHERE (SELECT count(*) FROM A WHERE A.ID = B.ID) < 1
I coudn't get any gain from transactions until I raised cache_size to a higher value i.e. PRAGMA cache_size=10000;
For Laravel 5.5.x
// Authentication Routes...
$this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
$this->post('login', 'Auth\LoginController@login');
$this->post('logout', 'Auth\LoginController@logout')->name('logout');
// Registration Routes...
$this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
$this->post('register', 'Auth\RegisterController@register');
// Password Reset Routes...
$this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
$this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
$this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
$this->post('password/reset', 'Auth\ResetPasswordController@reset');
I change the function to Match + make a change here with the slashes and its work: (http:// and https) both
function isValidUrl(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
}
The first thing to do is to check the details of the error message. For this you could use the LogCat App.
For me the problem was an error like
Cannot rename native library directory /data/app-lib/vmdl-... to /data/app-lib/com.xyz
The solution was to activate the common sense function in my brain and look for the com.xyz folder in the app-lib folder with ES-Explorer. I recognized that this folder was already there. So removing it solved the renaming problem and the apps can now install properly.
Use this code for read file with all type of extension file.
string[] sDirectoryInfo = Directory.GetFiles(SourcePath, "*.*");
In Kotlin there is now a cleaner way by using lambda functions, no need for interfaces:
class MyAdapter(val adapterOnClick: (Any) -> Unit) {
fun setItem(item: Any) {
myButton.setOnClickListener { adapterOnClick(item) }
}
}
class MyActivity {
override fun onCreate(savedInstanceState: Bundle?) {
var myAdapter = MyAdapter { item -> doOnClick(item) }
}
fun doOnClick(item: Any) {
}
}
You can use the fuser
command, like:
fuser file_name
You will receive a list of processes using the file.
You can use different flags with it, in order to receive a more detailed output.
You can find more info in the fuser's Wikipedia article, or in the man
pages.
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
Some of the answers involve creating a new public
method. Without doing this, use the Lazy<T>
class:
public class ViewModel
{
private Lazy<ObservableCollection<TData>> Data;
async public ViewModel()
{
Data = new Lazy<ObservableCollection<TData>>(GetDataTask);
}
public ObservableCollection<TData> GetDataTask()
{
Task<ObservableCollection<TData>> task;
//Create a task which represents getting the data
return task.GetAwaiter().GetResult();
}
}
To use Data
, use Data.Value
.
Try this:
u=open("url.txt","r")
url=u.read().replace('\n','')
print(url)
This is because of using integer indices (ix
selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).
*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:
df.iloc[-3:]
see the docs.
As Wes points out, in this specific case you should just use tail!
You can specify linker flags in target_link_libraries.
You can also use Scanner :
Scanner s = new Scanner(MyString);
s.nextInt();
The previous answers all state that you can do the following:
var d = eval(net_datetime.slice(1, -1));
However, this doesn't work in either Chrome or FF because what's getting evaluated literally is:
// returns the current timestamp instead of the specified epoch timestamp
var d = Date([epoch timestamp]);
The correct way to do this is:
var d = eval("new " + net_datetime.slice(1, -1)); // which parses to
var d = new Date([epoch timestamp]);
I used below logic while saving a .png format. This is to ensure the file is already existing or not.. if exist then saving it by adding 1 in the filename
Bitmap btImage = new Bitmap("D:\\Oldfoldername\\filename.png");
string path="D:\\Newfoldername\\filename.png";
int Count=0;
if (System.IO.File.Exists(path))
{
do
{
path = "D:\\Newfoldername\\filename"+"_"+ ++Count + ".png";
} while (System.IO.File.Exists(path));
}
btImage.Save(path, System.Drawing.Imaging.ImageFormat.Png);
Iterator.remove()
is safe, you can use it like this:
List<String> list = new ArrayList<>();
// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
// Iterator<String> iterator = list.iterator();
// while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String string = iterator.next();
if (string.isEmpty()) {
// Remove the current element from the iterator and the list.
iterator.remove();
}
}
Note that Iterator.remove()
is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
Source: docs.oracle > The Collection Interface
And similarly, if you have a ListIterator
and want to add items, you can use ListIterator#add
, for the same reason you can use Iterator#remove
— it's designed to allow it.
In your case you tried to remove from a list, but the same restriction applies if trying to put
into a Map
while iterating its content.
In Windows 10, it's still 8191 characters...at least on my machine.
It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.
Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.
echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat
No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:
select * from table1 where somedate between '2000/01/01' and '2099/12/31'
The separator needs to be a /
and it needs to be surrounded by single '
quotes.
There is often the tip to use 'echo.'
But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.
You could use echo(
. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.
More about the different ECHO:/\
variants is at DOS tips: ECHO. FAILS to give text or blank line.
The above answer for webkit appearance worked, but the button still looked kind pale/dull compared to the browser on other devices/desktop. I also had to set opacity to full (ranges from 0 to 1)
-webkit-appearance:none;
opacity: 1
After setting the opacity, the button looked the same on all the different devices/emulator/desktop.
Leave your email.php code the same, but replace this JavaScript code:
var name = $("#form_name").val();
var email = $("#form_email").val();
var text = $("#msg_text").val();
var dataString = 'name='+ name + '&email=' + email + '&text=' + text;
$.ajax({
type: "POST",
url: "email.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
with this:
$.ajax({
type: "POST",
url: "email.php",
data: $(form).serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
So that your form input names match up.
df[df.col.str.contains("foo").fillna(False)]
use an enum type to indicate your ViewModel's State
public enum ViewModeType
{
Default,
Busy
//etc.
}
then in your ViewModels Base class use a property
public ViewModeType ViewMode
{
get { return this.viewMode; }
set
{
if (this.viewMode != value)
{
this.viewMode = value;
//You should notify property changed here
}
}
}
and in view trigger the ViewMode and if it is busy show busyindicator:
<Trigger Property="ViewMode" Value="Busy">
<!-- Show BusyIndicator -->
</Trigger>
Do not use more than one style attribute. Just seperate styles in the style attribute with ;
It is a block of inline CSS, so think of this as you would do CSS in a separate stylesheet.
So in this case its:
style="height:100px;width:100px;"
You can use this for any CSS style, so if you wanted to change the colour of the text to white:
style="height:100px;width:100px;color:#ffffff"
and so on.
However, it is worth using inline CSS sparingly, as it can make code less manageable in future. Using an external stylesheet may be a better option for this. It depends really on your requirements. Inline CSS does make for quicker coding.
In case you would like to use timeout middleware and exclude a specific route:
var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests
app.use('/my_route', function(req, res, next) {
req.clearTimeout(); // clear request timeout
req.setTimeout(20000); //set a 20s timeout for this request
next();
}).get('/my_route', function(req, res) {
//do something that takes a long time
});
JSONObject.java
takes whatever map you pass. It may be LinkedHashMap
or TreeMap
and it will take hashmap
only when the map is null .
Here is the constructor of JSONObject.java
class that will do the checking of map.
public JSONObject(Map paramMap)
{
this.map = (paramMap == null ? new HashMap() : paramMap);
}
So before building a json object construct LinkedHashMap
and then pass it to the constructor like this ,
LinkedHashMap<String, String> jsonOrderedMap = new LinkedHashMap<String, String>();
jsonOrderedMap.put("1","red");
jsonOrderedMap.put("2","blue");
jsonOrderedMap.put("3","green");
JSONObject orderedJson = new JSONObject(jsonOrderedMap);
JSONArray jsonArray = new JSONArray(Arrays.asList(orderedJson));
System.out.println("Ordered JSON Fianl CSV :: "+CDL.toString(jsonArray));
So there is no need to change the JSONObject.java
class . Hope it helps somebody .
All of the responses refer to BootStrap 2 typeahead, which is no longer present in BootStrap 3.
For anyone else directed here looking for an AJAX example using the new post-Bootstrap Twitter typeahead.js, here's a working example. The syntax is a little different:
$('#mytextquery').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
limit: 12,
async: true,
source: function (query, processSync, processAsync) {
processSync(['This suggestion appears immediately', 'This one too']);
return $.ajax({
url: "/ajax/myfilter.php",
type: 'GET',
data: {query: query},
dataType: 'json',
success: function (json) {
// in this example, json is simply an array of strings
return processAsync(json);
}
});
}
});
This example uses both synchronous (the call to processSync) and asynchronous suggestion, so you'd see some options appear immediately, then others are added. You can just use one or the other.
There are lots of bindable events and some very powerful options, including working with objects rather than strings, in which case you'd use your own custom display function to render your items as text.
To create a copy of the crop we want, we can do the following,
// Read img
cv::Mat img = cv::imread("imgFileName");
cv::Mat croppedImg;
// This line picks out the rectangle from the image
// and copies to a new Mat
img(cv::Rect(xMin,yMin,xMax-xMin,yMax-yMin)).copyTo(croppedImg);
// Display diff
cv::imshow( "Original Image", img );
cv::imshow( "Cropped Image", croppedImg);
cv::waitKey();
To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump
, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:
with g as outfile:
json.dump(hostDict, outfile,indent=2)
Using indent = 2
helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.
You should have 'name' attribute for your inputs. You need to add the rules dynamically, one option is to add them when the form submits.
And here is my solution that I've tested and it works:
<script type="text/javascript">
$(document).ready(function() {
var numberIncr = 1; // used to increment the name for the inputs
function addInput() {
$('#inputs').append($('<input class="comment" name="name'+numberIncr+'" />'));
numberIncr++;
}
$('form.commentForm').on('submit', function(event) {
// adding rules for inputs with class 'comment'
$('input.comment').each(function() {
$(this).rules("add",
{
required: true
})
});
// prevent default submit action
event.preventDefault();
// test if form is valid
if($('form.commentForm').validate().form()) {
console.log("validates");
} else {
console.log("does not validate");
}
})
// set handler for addInput button click
$("#addInput").on('click', addInput);
// initialize the validator
$('form.commentForm').validate();
});
</script>
And the html form part:
<form class="commentForm" method="get" action="">
<div>
<p id="inputs">
<input class="comment" name="name0" />
</p>
<input class="submit" type="submit" value="Submit" />
<input type="button" value="add" id="addInput" />
</div>
</form>
Good luck! Please approve answer if it suits you!
you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.
Not IsNull(Fields!W_O_Count.Value)
Try Character.getNumericValue(char)
.
String element = "el5";
int x = Character.getNumericValue(element.charAt(2));
System.out.println("x=" + x);
produces:
x=5
The nice thing about getNumericValue(char)
is that it also works with strings like "el?"
and "el?"
where ?
and ?
are the digits 5 in Eastern Arabic and Hindi/Sanskrit respectively.
PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:
import sip
sip.setapi('QString', 2)
With this API, QtCore.QString
class is no longer available and self.ui.comboBox.currentText()
will return a Python string or unicode object.
See Selecting Incompatible APIs from the doc.
After calling an request, set timeout to initialize slick slider.
var options = {
arrows: false,
slidesToShow: 1,
variableWidth: true,
centerPadding: '10px'
}
$.ajax({
type: "GET",
url: review_url+"?page="+page,
success: function(result){
setTimeout(function () {
$(".reviews-page-carousel").slick(options)
}, 500);
}
})
Do not initialize slick slider at start. Just initialize after an AJAX with timeout. That should work for you.
function getUniqueNumber() {
function shuffle(str) {
var a = str.split("");
var n = a.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
}
var str = new Date().getTime() + (Math.random()*999 +1000).toFixed() //string
return Number.parseInt(shuffle(str));
}
I was facing the same problem and found out that my connection string had an extra double-quote character in the middle of the connection string.
Another programmatically approach;
final Button btn = (Button) findViewById(R.id.btnSize);
final float[] size = {12};
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
size[0] +=2;
btn.setTextSize(size[0] +2);
}
});
Every time you click your button, Button text will be change (+2px size). You can add another button and change size -2px too. If you want to save size for another openings, you may use Shared Preference interface.
var d = new Date();
d.setMonth(d.getMonth() - 3);
This works for January. Run this snippet:
var d = new Date("January 14, 2012");_x000D_
console.log(d.toLocaleDateString());_x000D_
d.setMonth(d.getMonth() - 3);_x000D_
console.log(d.toLocaleDateString());
_x000D_
There are some caveats...
A month is a curious thing. How do you define 1 month? 30 days? Most people will say that one month ago means the same day of the month on the previous month citation needed. But more than half the time, that is 31 days ago, not 30. And if today is the 31st of the month (and it isn't August or Decemeber), that day of the month doesn't exist in the previous month.
Interestingly, Google agrees with JavaScript if you ask it what day is one month before another day:
It also says that one month is 30.4167 days long:
So, is one month before March 31st the same day as one month before March 28th, 3 days earlier? This all depends on what you mean by "one month before". Go have a conversation with your product owner.
If you want to do like momentjs does, and correct these last day of the month errors by moving to the last day of the month, you can do something like this:
const d = new Date("March 31, 2019");_x000D_
console.log(d.toLocaleDateString());_x000D_
const month = d.getMonth();_x000D_
d.setMonth(d.getMonth() - 1);_x000D_
while (d.getMonth() === month) {_x000D_
d.setDate(d.getDate() - 1);_x000D_
}_x000D_
console.log(d.toLocaleDateString());
_x000D_
If your requirements are more complicated than that, use some math and write some code. You are a developer! You don't have to install a library! You don't have to copy and paste from stackoverflow! You can develop the code yourself to do precisely what you need!
You can pass the JVM this param
-Duser.timezone
For example
-Duser.timezone=Europe/Sofia
and this should do the trick. Setting the environment variable TZ also does the trick on Linux.
Another worked solution for me.
serever->security->logins->new logins->General->
create your user name as login name,Click sql server authentication add passwords
uncheck the password verification three checkboxes . This will work.
Remeber to change the server properties ->Security from Server authentication
to SQL Server and Windows Authentication mode
docker system prune
will do the trick, it removes
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all dangling build cache
But use it, with the caution!
As an alternative, if there's not a specific reason to use Math.random()
, use Random.nextInt()
:
import java.util.Random;
Random rnd = new Random();
int abc = rnd.nextInt(100); // +1 if you want 1-100, otherwise will be 0-99.
SO what I change is I load upload library each time
$config = array();
$config['upload_path'] = $filePath;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$files = $_FILES;
$count = count($_FILES['nameUpload']['name']);
for($i=0; $i<$count; $i++)
{
$this->load->library('upload', $config);
$_FILES['nameUpload']['name']= $files['nameUpload']['name'][$i];
$_FILES['nameUpload']['type']= $files['nameUpload']['type'][$i];
$_FILES['nameUpload']['tmp_name']= $files['nameUpload']['tmp_name'][$i];
$_FILES['nameUpload']['error']= $files['nameUpload']['error'][$i];
$_FILES['nameUpload']['size']= $files['nameUpload']['size'][$i];
$this->upload->do_upload('nameUpload');
}
And it work for me.
You can use
<%
Response.Write("Version: " + System.Environment.Version.ToString());
%>
That will get the currently running version. You can check the registry for all installed versions at:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
Here raw_input
is string
, so if you wanted to check, if var>3
then you should convert next to double, ie float(next)
and do as you would do if float(next)>3
:, but in most cases
I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.
ALTER TABLE users DROP id
The above sql can be run via sql query or as php. This will delete the id column.
Then re add it again, via the code below:
ALTER TABLE `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.
List<string> empnames = emplist.Select(e => e.Ename).ToList();
This is an example of Projection in Linq. Followed by a ToList
to resolve the IEnumerable<string>
into a List<string>
.
Alternatively in Linq syntax (head compiled):
var empnamesEnum = from emp in emplist
select emp.Ename;
List<string> empnames = empnamesEnum.ToList();
Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).
For example, you can project an enumerable of Employee
to an enumerable of Tuple<int, string>
like so:
var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));
For anaconda installation, first pick a channel which has the latest version of tensorflow binary. Usually, the latest versions are available at the channel conda-forge
. Then simply do:
conda update -f -c conda-forge tensorflow
This will upgrade your existing tensorflow installation to the very latest version available. As of this writing, the latest version is 1.4.0-py36_0
For URL or file, use json.load()
. For string with .json content, use json.loads()
.
#! /usr/bin/python
import json
# from pprint import pprint
json_file = 'my_cube.json'
cube = '1'
with open(json_file) as json_data:
data = json.load(json_data)
# pprint(data)
print "Dimension: ", data['cubes'][cube]['dim']
print "Measures: ", data['cubes'][cube]['meas']
You could just loop the rows and read the same cell from each row (doesn't this comprise a column?).
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
I got this error when my .env
file was not set up properly. Make sure you have a .env
file with valid database login credentials.
Option 1. Using boost library, you can declare the string as below
const boost::string_view helpText = "This is very long help text.\n"
"Also more text is here\n"
"And here\n"
// Pass help text here
setHelpText(helpText);
Option 2. If boost is not available in your project, you can use std::string_view() in modern C++.
Direct answer: Go to Files>>Import>>Git>>Project From Git (you should have GIT installed on Eclips)
On bulk, you can always delete the row before the insert. A deletion of a row that doesn't exist doesn't cause an error, so its safely skipped.
First add the import line:
from pyspark.sql.functions import min, max
df.agg(min("age")).show()
+--------+
|min(age)|
+--------+
| 29|
+--------+
df.agg(max("age")).show()
+--------+
|max(age)|
+--------+
| 77|
+--------+
easy:
location.href.replace(/^http/, 'ws') + '/to/ws'
// or if you hate regexp:
location.href.replace('http://', 'ws://').replace('https://', 'wss://') + '/to/ws'
Here's some code I use to deal with this.
First we show the element, which will typically set the display type to "block" via .show() function, and then set the CSS rule to "visible":
jQuery( '.element' ).show().css( 'visibility', 'visible' );
Or, assuming that the class that is hiding the element is called hidden, such as in Twitter Bootstrap, toggleClass() can be useful:
jQuery( '.element' ).toggleClass( 'hidden' );
Lastly, if you want to chain functions, perhaps with fancy with a fading effect, you can do it like so:
jQuery( '.element' ).css( 'visibility', 'visible' ).fadeIn( 5000 );
Write below code in your MainActivity.java file instead of your code.
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i("clicks","You Clicked B1");
Intent i=new Intent(MainActivity.this, MainActivity2.class);
startActivity(i);
}
}
And Declare MainActivity2 into your Androidmanifest.xml file using below code.
<activity
android:name=".MainActivity2"
android:label="@string/title_activity_main">
</activity>
I solve this issue by running following command
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
hope it helps
If the auditing is enabled on the server, just simply use
SELECT *
FROM ALL_TAB_MODIFICATIONS
WHERE TABLE_NAME IN ()
You can use trunc and to_date as follows:
select TO_CHAR (g.FECHA, 'DD-MM-YYYY HH24:MI:SS') fecha_salida, g.NUMERO_GUIA, g.BOD_ORIGEN, g.TIPO_GUIA, dg.DOC_NUMERO, dg.*
from ils_det_guia dg, ils_guia g
where dg.NUMERO_GUIA = g.NUMERO_GUIA and dg.TIPO_GUIA = g.TIPO_GUIA and dg.BOD_ORIGEN = g.BOD_ORIGEN
and dg.LAB_CODIGO = 56
and trunc(g.FECHA) > to_date('01/02/15','DD/MM/YY')
order by g.FECHA;
I see this has been answered, but it seems like you could avoid all of this 'remapping' of the enter key by simply hooking your validation into the AcceptButton on a form. ie. you have 3 textboxes (txtA,txtB,txtC) and an 'OK' button set to be AcceptButton (and TabOrder set properly). So, if in txtA and you hit enter, if the data is invalid, your focus will stay in txtA, but if it is valid, assuming the other txts need input, validation will just put you into the next txt that needs valid input thus simulating TAB behaviour... once all txts have valid input, pressing enter will fire a succsessful validation and close form (or whatever...) Make sense?
Wow, so many answers. For solid database versioning you need to version control the code that changes your database. Some CMS offer configuration management tools, such as the one in Drupal 8. Here is an overview with practical steps to arrange your workflow and ensure the database configuration is versioned, even in team environments:
Probably you don't have the service in your manifest, or it does not have an <intent-filter>
that matches your action. Examining LogCat (via adb logcat
, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.
More likely, you should start the service via:
startService(new Intent(this, UpdaterServiceManager.class));
Above points are correct and I want to add some more important points about Static keyword.
Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).
so you will get a doubt that what is the use of this right???
example: static int a=10;(1 program)
just now I told if you use static keyword for variables or for method it will store in permanent memory right.
so I declared same variable with keyword static in other program with different value.
example: static int a=20;(2 program)
the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.
In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.
overall i can say that,if we use static keyword
1.we can save memory
2.we can avoid duplicates
3.No need of creating object in-order to access static variable with the help of class name you can access it.
In this function pass string that you want to assign in label and pass font size in place of self.activityFont and pass label width in place of 235, now you get label height according to your string. it will work fine.
-(float)calculateLabelStringHeight:(NSString *)answer
{
CGRect textRect = [answer boundingRectWithSize: CGSizeMake(235, 10000000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.activityFont} context:nil];
return textRect.size.height;
}
<button style="position: absolute; left: 20%; right: 20%; bottom: 5%;"> Button </button>
Try this:
Select u.[username]
,u.[ip]
,q.[time_stamp]
From [users] As u
Inner Join (
Select [username]
,max(time_stamp) as [time_stamp]
From [users]
Group By [username]) As [q]
On u.username = q.username
And u.time_stamp = q.time_stamp
If you are on osx and using an emulator, you can view your console.log
s directly in safari web inspector.
Safari => Development => Simulator - [your simulator version here] => JSContext
Try disabling the Instant run in Settings.
You can do this using the jquery 'keydown' event handle
$( "#start" ).on( "keydown", function(event) {
if(event.which == 13)
alert("Entered!");
});
AFAIK, fragments cannot hold other fragments.
UPDATE
With current versions of the Android Support package -- or native fragments on API Level 17 and higher -- you can nest fragments, by means of getChildFragmentManager()
. Note that this means that you need to use the Android Support package version of fragments on API Levels 11-16, because even though there is a native version of fragments on those devices, that version does not have getChildFragmentManager()
.
Remove the existing Debug Configuration and create a new one. That should resolve the problem.
There is also a nice nuget package. It will pull the dll to your packages folder. You will need to add the reference to the dll manually.
NOTE: This package is not an official Microsoft package.
Git doesn't really store history the way you think it does. It calculates history at run-time based on an ancestor chain. If your ancestry is missing blobs, trees, or commits then you may not be able to fully recover your history.
The first thing you can try is to restore the missing items from backup. For example, see if you have a backup of the commit stored as .git/objects/98/4c11abfc9c2839b386f29c574d9e03383fa589
. If so you can restore it.
You may also want to look into git-verify-pack and git-unpack-objects in the event that the commit has already been packed up and you want to return it to a loose object for the purposes of repository surgery.
If you can't replace the missing items from a backup, you may be able to excise the missing history. For example, you might examine your history or reflog to find an ancestor of commit 984c11abfc9c2839b386f29c574d9e03383fa589. If you find one intact, then:
If it works, you will of course lose the intervening history. At this point, if you have a working history log, then it's a good idea to prune your history and reflogs of all unreachable commits and objects.
If your repository is still broken, then hopefully you have an uncorrupted backup or clone you can restore from. If not, but your current working directory contains valid files, then you can always re-initialize Git. For example:
rm -rf .git
git init
git add .
git commit -m 'Re-initialize repository without old history.'
It's drastic, but it may be your only option if your repository history is truly unrecoverable. YMMV.
You may try this : ( It works on 11g and it returns all column name from a table , here test_tbl is the table name and user_tab_columns are user permitted table's columns )
select COLUMN_NAME from user_tab_columns
where table_name='test_tbl';
I've never seen that before...but I have seen:
#if (DEBUG == FALSE)
and
#if (!DEBUG)
That work for ya?
var appBanners = document.getElementsByClassName('appBanner');
for (var i = 0; i < appBanners.length; i ++) {
appBanners[i].style.display = 'none';
}
If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1
, column2
, column3
like in this code snippet
while IFS=$'\t' read -r column1 column2 column3 ; do
printf "%b\n" "column1<${column1}>"
printf "%b\n" "column2<${column2}>"
printf "%b\n" "column3<${column3}>"
done < "myfile"
to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN
is not a good idea to do so).
As you already found the -T flag that create a PTY, I will just respond to the second part:
shell request failed on channel 0
You should pass a command:
ssh [email protected] -p 22 help
After reading back the manual here: https://www.jenkins.io/doc/book/managing/cli/, I find it not really clear that it would not work without a command. But as stated by @U.V., the ssh interface is not a console interface, rather a connection utility. So you need to pass a command...
If someone from the "jenkins" team pass accross this post, it would be great that if we pass no command, the help would show up :-)
You can use anonymous types for example:
var empData = from res in _db.EMPLOYEEs
where res.EMAIL == givenInfo || res.USER_NAME == givenInfo
select new { res.EMAIL, res.USER_NAME };
The biggest issue being missed by most solutions here is that an element's width is often changed by CSS based on where it is scoped in html.
If I was to determine offsetWidth of an element by appending a clone of it to body when it has styles that only apply in its current scope I would get the wrong width.
for example:
//css
.module-container .my-elem{ border: 60px solid black; }
now when I try to determine my-elem's width in context of body it will be out by 120px. You could clone the module container instead, but your JS shouldn't have to know these details.
I haven't tested it but essentially Soul_Master's solution appears to be the only one that could work properly. But unfortunately looking at the implementation it will likely be costly to use and bad for performance (as most of the solutions presented here are as well.)
If at all possible then use visibility: hidden instead. This will still render the element, allowing you to calculate width without all the fuss.
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
If you have previous apk file with you(backup) then use jarSigner to extract certificate from that that apk, then use that key or use keytool to clone that certificate, may be that will help... Helpful links are jarsigner docs and keytool docs.
If all you want is the UNIX command line tools I'd suggest not installing Cygwin. Cygwin wants to turn your Windows PC into a UNIX Workstation which is why it likes to install all its packages.
Have a look at GnuWin32 instead. It's Windows ports of the command line tools and nothing else. Here is the installer for the GnuWin32 diff.exe
. There are offline installers for all the common tools.
(You asked for offline installers but in case you ever want one later there is a tool which will download and install everything for you.)
Method 2: make an offline install zip file for cygwin.
Don't mess with saving packages because the installed directory for cygwin can be canned in a zip file and expanded whenever you need it on any computer.
Download Cygwin installer
pick packages you want installed from gui.
hit install and wait a really long time for everything to download.
zip up the C:\Cygwin folder. Now you have your offline zip file for installing cygwin on any machine.
Unzip this file on whatever computer you like. set cmd.exe paths appropriately to point to cygwin bin directory under windows control panel.
The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.
Try with:
select TO_CHAR(dates,'dd/MM/yyy hh24:mi') from ( SELECT min (TO_DATE(a.PAYM_DATE)) as dates from user_payment a )
I had this same issue and when I had an incorrect IP for session.save_path for memcached sessions. Changing it to the correct IP fixed the problem.
As from MSDN for GetChanges
A filtered copy of the DataTable that can have actions performed on it, and later be merged back in the DataTable using Merge. If no rows of the desired DataRowState are found, the method returns Nothing (null).
dataTable1
is null so just check before you iterate over it.
/usr/bin/swiftc --version
Using the accepted solution, I was finding that my "1.1" (when using the .floatValue conversion) would get converted to 1.10000002384186, which was not what I wanted. However, if I used the .doubleValue instead, I would get the 1.1 that I wanted.
So for example, instead of using the accepted solution, I used this instead:
var WageConversion = (Wage.text as NSString).doubleValue
In my case I did not need double-precision, but using the .floatValue was not giving me the proper result.
Just wanted to add this to the discussion in case someone else had been running into the same issue.
If you really want to kill a process immediately, you send it a KILL signal instead of a TERM signal (the latter a request to stop, the first will take effect immediately without any cleanup). It is easy to do:
kill -KILL <pid>
Be aware however that depending on the program you are stopping, its state may get badly corrupted when doing so. You normally only want to send a KILL signal when normal termination does not work. I'm wondering what the underlying problem is that you try to solve and whether killing is the right solution.
I had the same problem, and my solution was to eliminate the line
android:screenOrientation="portrait"
and then add this in the activity:
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.
You can check this by running in Windows PowerShell:
> Get-Service ssh-agent
And then check the output of status is not running.
Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent
Then check that the service has been disabled by running
> Get-Service ssh-agent | Select StartType
StartType
---------
Disabled
I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:
> Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Alternatively, you can set it through the GUI if you prefer.
When figuring out if an url exists from php there are a few things to pay attention to:
Keep in mind that whatever method you use, it takes time to wait for a response.
All code might (and probably will) halt untill you either know the result or the requests have timed out.
For example: the code below could take a LONG time to display the page if the urls are invalid or unreachable:
<?php
$urls = getUrls(); // some function getting say 10 or more external links
foreach($urls as $k=>$url){
// this could potentially take 0-30 seconds each
// (more or less depending on connection, target site, timeout settings...)
if( ! isValidUrl($url) ){
unset($urls[$k]);
}
}
echo "yay all done! now show my site";
foreach($urls as $url){
echo "<a href=\"{$url}\">{$url}</a><br/>";
}
The functions below could be helpfull, you probably want to modify them to suit your needs:
function isValidUrl($url){
// first do some quick sanity checks:
if(!$url || !is_string($url)){
return false;
}
// quick check url is roughly a valid http request: ( http://blah/... )
if( ! preg_match('/^http(s)?:\/\/[a-z0-9-]+(\.[a-z0-9-]+)*(:[0-9]+)?(\/.*)?$/i', $url) ){
return false;
}
// the next bit could be slow:
if(getHttpResponseCode_using_curl($url) != 200){
// if(getHttpResponseCode_using_getheaders($url) != 200){ // use this one if you cant use curl
return false;
}
// all good!
return true;
}
function getHttpResponseCode_using_curl($url, $followredirects = true){
// returns int responsecode, or false (if url does not exist or connection timeout occurs)
// NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings))
// if $followredirects == false: return the FIRST known httpcode (ignore redirects)
// if $followredirects == true : return the LAST known httpcode (when redirected)
if(! $url || ! is_string($url)){
return false;
}
$ch = @curl_init($url);
if($ch === false){
return false;
}
@curl_setopt($ch, CURLOPT_HEADER ,true); // we want headers
@curl_setopt($ch, CURLOPT_NOBODY ,true); // dont need body
@curl_setopt($ch, CURLOPT_RETURNTRANSFER ,true); // catch output (do NOT print!)
if($followredirects){
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,true);
@curl_setopt($ch, CURLOPT_MAXREDIRS ,10); // fairly random number, but could prevent unwanted endless redirects with followlocation=true
}else{
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,false);
}
// @curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); // fairly random number (seconds)... but could prevent waiting forever to get a result
// @curl_setopt($ch, CURLOPT_TIMEOUT ,6); // fairly random number (seconds)... but could prevent waiting forever to get a result
// @curl_setopt($ch, CURLOPT_USERAGENT ,"Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1"); // pretend we're a regular browser
@curl_exec($ch);
if(@curl_errno($ch)){ // should be 0
@curl_close($ch);
return false;
}
$code = @curl_getinfo($ch, CURLINFO_HTTP_CODE); // note: php.net documentation shows this returns a string, but really it returns an int
@curl_close($ch);
return $code;
}
function getHttpResponseCode_using_getheaders($url, $followredirects = true){
// returns string responsecode, or false if no responsecode found in headers (or url does not exist)
// NOTE: could potentially take up to 0-30 seconds , blocking further code execution (more or less depending on connection, target site, and local timeout settings))
// if $followredirects == false: return the FIRST known httpcode (ignore redirects)
// if $followredirects == true : return the LAST known httpcode (when redirected)
if(! $url || ! is_string($url)){
return false;
}
$headers = @get_headers($url);
if($headers && is_array($headers)){
if($followredirects){
// we want the last errorcode, reverse array so we start at the end:
$headers = array_reverse($headers);
}
foreach($headers as $hline){
// search for things like "HTTP/1.1 200 OK" , "HTTP/1.0 200 OK" , "HTTP/1.1 301 PERMANENTLY MOVED" , "HTTP/1.1 400 Not Found" , etc.
// note that the exact syntax/version/output differs, so there is some string magic involved here
if(preg_match('/^HTTP\/\S+\s+([1-9][0-9][0-9])\s+.*/', $hline, $matches) ){// "HTTP/*** ### ***"
$code = $matches[1];
return $code;
}
}
// no HTTP/xxx found in headers:
return false;
}
// no headers :
return false;
}
You need to #include <stdlib.h>
. Otherwise it's defined as int malloc()
which is incompatible with the built-in type void *malloc(size_t)
.
If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.
$(window).load(function() {
$('form').get(0).reset(); //clear form data on page load
});
Here is a tail recursive version. Compared to the for-comprehensions it is a bit cryptic, admittedly, but I'd say its functional :)
def run(start:Int) = {
@tailrec
def tr(i:Int, largest:Int):Int = tr1(i, i, largest) match {
case x if i > 1 => tr(i-1, x)
case _ => largest
}
@tailrec
def tr1(i:Int,j:Int, largest:Int):Int = i*j match {
case x if x < largest || j < 2 => largest
case x if x.toString.equals(x.toString.reverse) => tr1(i, j-1, x)
case _ => tr1(i, j-1, largest)
}
tr(start, 0)
}
As you can see, the tr function is the counterpart of the outer for-comprehensions, and tr1 of the inner one. You're welcome if you know a way to optimize my version.
It sounds like you need to set up passwordless sudo. Try:
%admin ALL=(ALL) NOPASSWD: osascript myscript.scpt
Also comment out the following line (in /etc/sudoers via visudo), if it is there:
Defaults requiretty
Symfony 2.1
$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');
return $response;
Symfony 2.2 and higher
You have special JsonResponse class, which serialises array to JSON:
return new JsonResponse(array('name' => $name));
But if your problem is How to serialize entity then you should have a look at JMSSerializerBundle
Assuming that you have it installed, you'll have simply to do
$serializedEntity = $this->container->get('serializer')->serialize($entity, 'json');
return new Response($serializedEntity);
You should also check for similar problems on StackOverflow:
The shape
attribute for numpy arrays returns the dimensions of the array. If Y
has n
rows and m
columns, then Y.shape
is (n,m)
. So Y.shape[0]
is n
.
In [46]: Y = np.arange(12).reshape(3,4)
In [47]: Y
Out[47]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In [48]: Y.shape
Out[48]: (3, 4)
In [49]: Y.shape[0]
Out[49]: 3
Ajax is a technology / paradigm, whereas jquery is a library (which provides - besides other nice functionality - a convenient wrapper around ajax) - thus you can't compare them.
The best you can do with Python is to obscure things.
You may be able to add some additional obscurity by encrypting part of it and decrypting it on the fly and passing it to eval(). But no matter what you do someone can break it.
None of this will stop a determined attacker from disassembling the bytecode or digging through your api with help, dir, etc.
You can chain class selectors without a space between them:
.a.b {
color: #666;
}
Note that, if it matters to you, IE6 treats .a.b
as .b
, so in that browser both div.a.b
and div.b
will have gray text. See this answer for a comparison between proper browsers and IE6.
It shouldn't matter if the word has an even or odd amount fo letters:
def is_palindrome(word):
if word == word[::-1]:
return True
else:
return False
BASED ON LARAVEL 5.7 & ABOVE
To get all segments of current URL:
$current_uri = request()->segments();
To get segment posts
from http://example.com/users/posts/latest/
NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be users
and segment(1) will be posts
.
//get segment 0
$segment_users = request()->segment(0); //returns 'users'
//get segment 1
$segment_posts = request()->segment(1); //returns 'posts'
You may have noted that the segment method only works with the current URL ( url()->current()
). So I designed a method to work with previous URL too by cloning the segment()
method:
public function index()
{
$prev_uri_segments = $this->prev_segments(url()->previous());
}
/**
* Get all of the segments for the previous uri.
*
* @return array
*/
public function prev_segments($uri)
{
$segments = explode('/', str_replace(''.url('').'', '', $uri));
return array_values(array_filter($segments, function ($value) {
return $value !== '';
}));
}
Just to extend the accepted answer:
From version 2.7
and 3.1
python has got set
literal {}
in form of usage {1,2,3}
, but {}
itself still used for empty dict.
Python 2.7 (first line is invalid in Python <2.7)
>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>
Python 3.x
>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>
More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes
Clip.exe is an executable in Windows to set the clipboard. Note that this does not work for other operating systems other than Windows, which still sucks.
/// <summary>
/// Sets clipboard to value.
/// </summary>
/// <param name="value">String to set the clipboard to.</param>
public static void SetClipboard(string value)
{
if (value == null)
throw new ArgumentNullException("Attempt to set clipboard with null");
Process clipboardExecutable = new Process();
clipboardExecutable.StartInfo = new ProcessStartInfo // Creates the process
{
RedirectStandardInput = true,
FileName = @"clip",
};
clipboardExecutable.Start();
clipboardExecutable.StandardInput.Write(value); // CLIP uses STDIN as input.
// When we are done writing all the string, close it so clip doesn't wait and get stuck
clipboardExecutable.StandardInput.Close();
return;
}
You mean fast enumeration? You question is very unclear.
A normal for loop would look a bit like this:
unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{
// do loop stuff
id someObject = [someArray objectAtIndex:i];
}
And a loop with fast enumeration, which is optimized by the compiler, would look like this:
for(id someObject in someArray)
{
// do stuff with object
}
Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration
Study up on multidimensional arrays. This question might help.
You shall perform different detections of iPhone X depending on the actual need.
class var hasTopNotch: Bool {
if #available(iOS 11.0, tvOS 11.0, *) {
// with notch: 44.0 on iPhone X, XS, XS Max, XR.
// without notch: 24.0 on iPad Pro 12.9" 3rd generation, 20.0 on iPhone 8 on iOS 12+.
return UIApplication.shared.delegate?.window??.safeAreaInsets.top ?? 0 > 24
}
return false
}
class var hasBottomSafeAreaInsets: Bool {
if #available(iOS 11.0, tvOS 11.0, *) {
// with home indicator: 34.0 on iPhone X, XS, XS Max, XR.
// with home indicator: 20.0 on iPad Pro 12.9" 3rd generation.
return UIApplication.shared.delegate?.window??.safeAreaInsets.bottom ?? 0 > 0
}
return false
}
class var isIphoneXOrBigger: Bool {
// 812.0 on iPhone X, XS.
// 896.0 on iPhone XS Max, XR.
return UIScreen.main.bounds.height >= 812
}
Note: eventually mix it with UIDevice.current.userInterfaceIdiom == .phone
Note: this method requires to have a LaunchScreen storyboard or proper LaunchImages
class var isIphoneXOrLonger: Bool {
// 812.0 / 375.0 on iPhone X, XS.
// 896.0 / 414.0 on iPhone XS Max, XR.
return UIScreen.main.bounds.height / UIScreen.main.bounds.width >= 896.0 / 414.0
}
Note: this method requires to have a LaunchScreen storyboard or proper LaunchImages
Get the machine identifier and compare it to documented values:
class var isIphoneX: Bool {
var size = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: size)
sysctlbyname("hw.machine", &machine, &size, nil, 0)
let model = String(cString: machine)
return model == "iPhone10,3" || model == "iPhone10,6"
}
To include the simulator as a valid iPhone X in your analytics:
class var isIphoneX: Bool {
let model: String
if TARGET_OS_SIMULATOR != 0 {
model = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? ""
} else {
var size = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: size)
sysctlbyname("hw.machine", &machine, &size, nil, 0)
model = String(cString: machine)
}
return model == "iPhone10,3" || model == "iPhone10,6"
}
To include iPhone XS, XS Max and XR, simply look for models starting with "iPhone11,":
return model == "iPhone10,3" || model == "iPhone10,6" || model.starts(with: "iPhone11,")
import LocalAuthentication
/// will fail if user denies canEvaluatePolicy(_:error:)
class var canUseFaceID: Bool {
if #available(iOS 11.0, *) {
return LAContext().biometryType == .typeFaceID
}
return false
}
You can try the margin
property in the Container
. Wrap the TextField
inside a Container
and adjust the margin
property.
new Container(
margin: const EdgeInsets.only(right: 10, left: 10),
child: new TextField(
decoration: new InputDecoration(
hintText: 'username',
icon: new Icon(Icons.person)),
)
),
Another option would be to set the webroot path to the angular cli dist folder. In your Program.cs when configuring the WebHostBuilder just say
.UseWebRoot(Directory.GetCurrentDirectory() + "\\Frontend\\dist")
or whatever the path to your dist dir is.
Long story short you need to create a launch file. So, from Terminal:
sudo vi /Library/LaunchDaemons/com.mysql.mysql.plist
(If you are not familiar with vi, then press i to start inserting text)
This should be the content of your file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true />
<key>Label</key>
<string>com.mysql.mysqld</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/mysql/bin/mysqld_safe</string>
<string>--user=mysql</string>
</array>
</dict>
</plist>
press esc then : wq!enter
Then you need to give the file the right permissions and set it to load on startup.
sudo chown root:wheel /Library/LaunchDaemons/com.mysql.mysql.plist
sudo chmod 644 /Library/LaunchDaemons/com.mysql.mysql.plist
sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist
And that is it.
This will squash second commit into the first one:
A-B-C-... -> AB-C-...
git filter-branch --commit-filter '
if [ "$GIT_COMMIT" = <sha1ofA> ];
then
skip_commit "$@";
else
git commit-tree "$@";
fi
' HEAD
Commit message for AB will be taken from B (although I'd prefer from A).
Has the same effect as Uwe Kleine-König's answer, but works for non-initial A as well.
One requirement for remote debugging is that the windows account used to run SSMS be part of the sysadmin role. See this MSDN link: http://msdn.microsoft.com/en-us/library/cc646024%28v=sql.105%29.aspx
I resolved this by adding @Transactional
to the base/generic Hibernate DAO implementation class (the parent class which implements the saveOrUpdate() method inherited by the DAO I use in the main program), i.e. the @Transactional
needs to be specified on the actual class which implements the method. My assumption was instead that if I declared @Transactional
on the child class then it included all of the methods that were inherited by the child class. However it seems that the @Transactional
annotation only applies to methods implemented within a class and not to methods inherited by a class.
def eggs(someParameter):
del spam[3]
someParameter.insert(3, ' and cats.')
spam = ['apples', 'bananas', 'tofu', 'cats']
eggs(spam)
spam =(','.join(spam))
print(spam)
If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):
unsigned int l=0, removed=0;
for( unsigned int i=0; i<count; i++ ) {
if( array[i] != to_remove )
array[l++] = array[i];
else
removed++;
}
count -= removed;
A more explicit option is to project collection to an IEnumerable of KeyValuePair
and then convert it to a Dictionary.
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
For input field
<input id="PrimaryPhNumber" type="text" name="mobile" required
pattern="^[789]\d{9}$" minlenght="10" maxLength="10" placeholder="Eg: 9444400000"
class="inputBoxCss"/>
$('#PrimaryPhNumber').keyup(function (e) {
console.log(e)
let field=$(this)
if(Number(field.val()).toString()=="NaN"){
field.val('');
field.focus();
field[0].setCustomValidity('Please enter a valid phone number');
field[0].reportValidity()
$(":focus").css("border", "2px solid red");
}
})
[self score]; instead of @selector(score)
For integers I use this
function integer_or_null(value) {
if ((undefined === value) || (null === value)) {
return null;
}
if(value % 1 != 0) {
return null;
}
return value;
}
def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
print("Your SP balance is now 0.")
attributeConfirmation()
elif strength < 0:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif strength > balance:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
print("That is an invalid input. Restarting attribute selection.")
attributeSelection()
To be convert the image to byte array.The code is give below.
public byte[] ImageToByteArray(System.Drawing.Image images)
{
using (var _memorystream = new MemoryStream())
{
images.Save(_memorystream ,images.RawFormat);
return _memorystream .ToArray();
}
}
To be convert the Byte array to Image.The code is given below.The code is handle A Generic error occurred in GDI+
in Image Save.
public void SaveImage(string base64String, string filepath)
{
// image convert to base64string is base64String
//File path is which path to save the image.
var bytess = Convert.FromBase64String(base64String);
using (var imageFile = new FileStream(filepath, FileMode.Create))
{
imageFile.Write(bytess, 0, bytess.Length);
imageFile.Flush();
}
}
$('.update-cart').click(function(e) {
updateCartWidget();
e.stopPropagation();
e.preventDefault();
});
$('.update-cart').click(function() {
updateCartWidget();
return false;
});
The following methods achieve the exact same thing.
To round up an integer division you can use
import static java.lang.Math.abs;
public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}
or if both numbers are positive
public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}
Just a word on drawing (incorrect) conclusions from any of the performance measurement commands referred to in the answers. There are a number of pitfalls that should taken in consideration aside from looking to the bare invocation time of a (custom) function or command.
'Sjoemelsoftware' voted Dutch word of the year 2015
Sjoemelen means cheating, and the word sjoemelsoftware came into being due to the Volkswagen emissions scandal. The official definition is "software used to influence test results".
Personally, I think that "Sjoemelsoftware" is not always deliberately created to cheat test results but might originate from accommodating practical situation that are similar to test cases as shown below.
As an example, using the listed performance measurement commands, Language Integrated Query (LINQ)(1), is often qualified as the fasted way to get something done and it often is, but certainly not always! Anybody who measures a speed increase of a factor 40 or more in comparison with native PowerShell commands, is probably incorrectly measuring or drawing an incorrect conclusion.
The point is that some .Net classes (like LINQ) using a lazy evaluation (also referred to as deferred execution(2)). Meaning that when assign an expression to a variable, it almost immediately appears to be done but in fact it didn't process anything yet!
Let presume that you dot-source your . .\Dosomething.ps1
command which has either a PowerShell or a more sophisticated Linq expression (for the ease of explanation, I have directly embedded the expressions directly into the Measure-Command
):
$Data = @(1..100000).ForEach{[PSCustomObject]@{Index=$_;Property=(Get-Random)}}
(Measure-Command {
$PowerShell = $Data.Where{$_.Index -eq 12345}
}).totalmilliseconds
864.5237
(Measure-Command {
$Linq = [Linq.Enumerable]::Where($Data, [Func[object,bool]] { param($Item); Return $Item.Index -eq 12345})
}).totalmilliseconds
24.5949
The result appears obvious, the later Linq command is a about 40 times faster than the first PowerShell command. Unfortunately, it is not that simple...
Let's display the results:
PS C:\> $PowerShell
Index Property
----- --------
12345 104123841
PS C:\> $Linq
Index Property
----- --------
12345 104123841
As expected, the results are the same but if you have paid close attention, you will have noticed that it took a lot longer to display the $Linq
results then the $PowerShell
results.
Let's specifically measure that by just retrieving a property of the resulted object:
PS C:\> (Measure-Command {$PowerShell.Property}).totalmilliseconds
14.8798
PS C:\> (Measure-Command {$Linq.Property}).totalmilliseconds
1360.9435
It took about a factor 90 longer to retrieve a property of the $Linq
object then the $PowerShell
object and that was just a single object!
Also notice an other pitfall that if you do it again, certain steps might appear a lot faster then before, this is because some of the expressions have been cached.
Bottom line, if you want to compare the performance between two functions, you will need to implement them in your used case, start with a fresh PowerShell session and base your conclusion on the actual performance of the complete solution.
(1) For more background and examples on PowerShell and LINQ, I recommend tihis site: High Performance PowerShell with LINQ
(2) I think there is a minor difference between the two concepts as with lazy evaluation the result is calculated when needed as apposed to deferred execution were the result is calculated when the system is idle
Just remove the (
and the )
on your SELECT statement:
insert into table2 (Name, Subject, student_id, result)
select Name, Subject, student_id, result
from table1;
You need to make use of Label Callback. A common example to round data values, the following example rounds the data to two decimal places.
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += Math.round(tooltipItem.yLabel * 100) / 100;
return label;
}
}
}
}
});
Now let me write the scenario where I used the label callback functionality.
Let's start with logging the arguments of Label Callback function, you will see structure similar to this here datasets, array comprises of different lines you want to plot in the chart. In my case it's 4, that's why length of datasets array is 4.
In my case, I had to perform some calculations on each dataset and have to identify the correct line, every-time I hover upon a line in a chart.
To differentiate different lines and manipulate the data of hovered tooltip based on the data of other lines I had to write this logic.
callbacks: {
label: function (tooltipItem, data) {
console.log('data', data);
console.log('tooltipItem', tooltipItem);
let updatedToolTip: number;
if (tooltipItem.datasetIndex == 0) {
updatedToolTip = tooltipItem.yLabel;
}
if (tooltipItem.datasetIndex == 1) {
updatedToolTip = tooltipItem.yLabel - data.datasets[0].data[tooltipItem.index];
}
if (tooltipItem.datasetIndex == 2) {
updatedToolTip = tooltipItem.yLabel - data.datasets[1].data[tooltipItem.index];
}
if (tooltipItem.datasetIndex == 3) {
updatedToolTip = tooltipItem.yLabel - data.datasets[2].data[tooltipItem.index]
}
return updatedToolTip;
}
}
Above mentioned scenario will come handy, when you have to plot different lines in line-chart and manipulate tooltip of the hovered point of a line, based on the data of other point belonging to different line in the chart at the same index.
If scope resolution :: had to be used outside the class then the respective function or variable should be declared as static
class Foo {
//Static variable
public static $static_var = 'static variable';
//Static function
static function staticValue() { return 'static function'; }
//function
function Value() { return 'Object'; }
}
echo Foo::$static_var . "<br/>"; echo Foo::staticValue(). "<br/>"; $foo = new Foo(); echo $foo->Value();
In the Facebook app control panel make sure you have a forward slash on the end of any specified URL if you are only specifying a folder name
i.e.
Page Tab URL: http://mypagetabserver.com/custom_tab/
from numpy.lib.scimath import logn
from math import e
#using: x - var
logn(e, x)
Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework
Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type
Finally, Rebuild the solution.
This solves the issue in the appropriate way
// Merge a row
ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
ws.Range("B2:D3").Row(1).Merge();
While a bit more cryptic than join
, you can also multiply the array by a string.
@arr * " "
In my case for avoiding that problem:
Be sure that you are dealing with Xcode 7, NOT lower versions. In lower version this flag does not exist.
Setup: Project>Build Settings>All>Build Options>Enable Bitcode = NO
Prevent browser cache is not a good idea depending on the case. Looking for a solution I found solutions like this:
<link rel="stylesheet" type="text/css" href="meu.css?v=<?=filemtime($file);?>">
the problem here is that if the file is overwritten during an update on the server, which is my scenario, the cache is ignored because timestamp is modified even the content of the file is the same.
I use this solution to force browser to download assets only if its content is modified:
<link rel="stylesheet" type="text/css" href="meu.css?v=<?=hash_file('md5', $file);?>">
This might work for you:
function foo() { bar(); }
function bar() { console.log(bar.caller.name); }
running foo() will output "foo" or undefined if you call from an anonymous function.
It works with constructors too, in which case it would output the name of the calling constructor (eg "Foo").
More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller
They claim it's non-standard, but also that it's supported by all major browsers: Firefox, Safari, Chrome, Opera and IE.
In your example, You don't need to. As a standard programming practice, all variables being referred to inside some code block, say for example try{} catch(){}
, and being referred to outside the block as well, you need to declare the variables outside the try block first e.g.
This is helpful when your equals method call throws some exception e.g. NullPointerException
;
boolean isMatch = false;
try{
isMatch = email1.equals (email2);
}catch(NullPointerException npe){
.....
}
System.out.print("Match=="+isMatch);
if(isMatch){
......
}
It won't be efficient, as you need to walk the list checking every item in it (O(n)). If you want efficiency, you can use dict of dicts. On the question, here's one possible way to find it (though, if you want to stick to this data structure, it's actually more efficient to use a generator as Brent Newey has written in the comments; see also tokland's answer):
>>> L = [{'id':'1234','name':'Jason'},
... {'id':'2345','name':'Tom'},
... {'id':'3456','name':'Art'}]
>>> [i for i,_ in enumerate(L) if _['name'] == 'Tom'][0]
1
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
You can use wildcard to do this as following
ArrayList<String> strList = (ArrayList<String>)(ArrayList<?>)(list);
For testing sometimes I do
fmt.Fprintln(os.Stdout, "hello")
Also, you can print to:
fmt.Fprintln(os.Stderr, "hello)
Dictionary is the most common, but you can use other types of collections, e.g. System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable, or any KeyValuePair collection
val jsonString =
"""
|{
| "languages": [{
| "name": "English",
| "is_active": true,
| "completeness": 2.5
| }, {
| "name": "Latin",
| "is_active": false,
| "completeness": 0.9
| }]
|}
""".stripMargin
val result = JSON.parseFull(jsonString).map {
case json: Map[String, List[Map[String, Any]]] =>
json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get
println(result)
assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.
import datetime
def utc_str_to_local_str(utc_str: str, utc_format: str, local_format: str):
"""
:param utc_str: UTC time string
:param utc_format: format of UTC time string
:param local_format: format of local time string
:return: local time string
"""
temp1 = datetime.datetime.strptime(utc_str, utc_format)
temp2 = temp1.replace(tzinfo=datetime.timezone.utc)
local_time = temp2.astimezone()
return local_time.strftime(local_format)
utc = '2018-10-17T00:00:00.111Z'
utc_fmt = '%Y-%m-%dT%H:%M:%S.%fZ'
local_fmt = '%Y-%m-%dT%H:%M:%S+08:00'
local_string = utc_str_to_local_str(utc, utc_fmt, local_fmt)
print(local_string) # 2018-10-17T08:00:00+08:00
for example, my timezone is '+08:00'. input utc = 2018-10-17T00:00:00.111Z, then I will get output = 2018-10-17T08:00:00+08:00
this code will give you latest post first, i think this answer is helpful.
mInstaList=(RecyclerView)findViewById(R.id.insta_list);
mInstaList.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mInstaList.setLayoutManager(layoutManager);
layoutManager.setStackFromEnd(true);
layoutManager.setReverseLayout(true);
Containers use the OS kernel. Windows Container utilize processes in order to run. So theoretically speaking Windows Containers cannot run on Linux.
However there are workarounds utilizing VMstyle solutions.
I Have found this solution which uses Vagrant and Packer on Mac, so it should work for Linux as well: https://github.com/StefanScherer/windows-docker-machine
This Vagrant environment creates a Docker Machine to work on your MacBook with Windows containers. You can easily switch between Docker for Mac Linux containers and the Windows containers.
building the headless Vagrant box
$ git clone https://github.com/StefanScherer/packer-windows $ cd packer-windows $ packer build --only=vmware-iso windows_2019_docker.json $ vagrant box add windows_2019_docker windows_2019_docker_vmware.box
Create the Docker Machine
$ git clone https://github.com/StefanScherer/windows-docker-machine $ cd windows-docker-machine $ vagrant up --provider vmware_fusion 2019
Switch to Windows containers
$ eval $(docker-machine env 2019)
In the Google docs, they've identified a pagespeed
filter that will load the script asynchronously:
ModPagespeedEnableFilters make_google_analytics_async
You can find the documentation here: https://developers.google.com/speed/pagespeed/module/filter-make-google-analytics-async
One thing to highlight is that the filter is considered high risk. From the docs:
The make_google_analytics_async filter is experimental and has not had extensive real-world testing. One case where a rewrite would cause errors is if the filter misses calls to Google Analytics methods that return values. If such methods are found, the rewrite is skipped. However, the disqualifying methods will be missed if they come before the load, are in attributes such as "onclick", or if they are in external resources. Those cases are expected to be rare.
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
Will the conditions be ORed or ANDed together?
Starts with: abc Ends with: xyz Contains: 123 Doesn't contain: 456
The OR version is fairly simple; as you said, it's mostly a matter of inserting pipes between individual conditions. The regex simply stops looking for a match as soon as one of the alternatives matches.
/^abc|xyz$|123|^(?:(?!456).)*$/
That fourth alternative may look bizarre, but that's how you express "doesn't contain" in a regex. By the way, the order of the alternatives doesn't matter; this is effectively the same regex:
/xyz$|^(?:(?!456).)*$|123|^abc/
The AND version is more complicated. After each individual regex matches, the match position has to be reset to zero so the next regex has access to the whole input. That means all of the conditions have to be expressed as lookaheads (technically, one of them doesn't have to be a lookahead, I think it expresses the intent more clearly this way). A final .*$
consummates the match.
/^(?=^abc)(?=.*xyz$)(?=.*123)(?=^(?:(?!456).)*$).*$/
And then there's the possibility of combined AND and OR conditions--that's where the real fun starts. :D
./src/components/BusinessesList.js
Line 51: React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array react-hooks/exhaustive-deps
It's not JS/React error but eslint (eslint-plugin-react-hooks) warning.
It's telling you that hook depends on function fetchBusinesses
, so you should pass it as dependency.
useEffect(() => {
fetchBusinesses();
}, [fetchBusinesses]);
It could result in invoking function every render if function is declared in component like:
const Component = () => {
/*...*/
//new function declaration every render
const fetchBusinesses = () => {
fetch('/api/businesses/')
.then(...)
}
useEffect(() => {
fetchBusinesses();
}, [fetchBusinesses]);
/*...*/
}
because every time function is redeclared with new reference
Correct way of doing this stuff is:
const Component = () => {
/*...*/
// keep function reference
const fetchBusinesses = useCallback(() => {
fetch('/api/businesses/')
.then(...)
}, [/* additional dependencies */])
useEffect(() => {
fetchBusinesses();
}, [fetchBusinesses]);
/*...*/
}
or just defining function in useEffect
'profiles'
from the table 'django_migrations'
.python manage.py makemigrations
and python manage.py migrate
command.I faced the same problem and I've found a pretty clean solution: After Html.fromHtml() you can run an AsyncTask that iterates over all the tags, fetches the images and then displays them.
Here you can find some code that you can use (but it needs some customization): https://gist.github.com/1190397
I know two ways to do this:
This will reset your database and reload your current schema with all:
rake db:reset db:migrate
This will destroy your db and then create it and then migrate your current schema:
rake db:drop db:create db:migrate
All data will be lost in both scenarios.
Negatives are your friend here:
SELECT Col1
FROM TABLE
WHERE Col1 like '%[^a-Z0-9]%'
Which says that you want any rows where Col1
consists of any number of characters, then one character not in the set a-Z0-9, and then any number of characters.
If you have a case sensitive collation, it's important that you use a range that includes both upper and lower case A
, a
, Z
and z
, which is what I've given (originally I had it the wrong way around. a
comes before A
. Z
comes after z
)
Or, to put it another way, you could have written your original WHERE
as:
Col1 LIKE '[!@#$%]'
But, as you observed, you'd need to know all of the characters to include in the []
.
The -Contains
operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
I think what you want is the -Match
operator:
"12-18" -Match "-"
Which returns True
.
Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match
operator uses regular expressions to perform text matching.
I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.
example:
linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));
see definition: http://man7.org/linux/man-pages/man7/socket.7.html
SO_LINGER
Sets or gets the SO_LINGER option. The argument is a linger
structure.
struct linger {
int l_onoff; /* linger active */
int l_linger; /* how many seconds to linger for */
};
When enabled, a close(2) or shutdown(2) will not return until
all queued messages for the socket have been successfully sent
or the linger timeout has been reached. Otherwise, the call
returns immediately and the closing is done in the background.
When the socket is closed as part of exit(2), it always
lingers in the background.
More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required
I Tried this one and it worked for me for all decimal/integer numbers greater than zero
Allows white space: ^\s*(?=.*[1-9])\d*(?:\.\d{1,2})?\s*$
No white space: ^(?=.*[1-9])\d*(?:\.\d{1,2})?$
Do the loop in the normal way, the java.util.ConcurrentModificationException
is an error related to the elements that are accessed.
So try:
for(int i = 0; i < list.size(); i++){
lista.get(i).action();
}
Here are some real-world examples of the types of relationships:
A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.
To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).
For example:
CREATE TABLE Gov(
GID number(6) PRIMARY KEY,
Name varchar2(25),
Address varchar2(30),
TermBegin date,
TermEnd date
);
CREATE TABLE State(
SID number(3) PRIMARY KEY,
StateName varchar2(15),
Population number(10),
SGID Number(4) REFERENCES Gov(GID),
CONSTRAINT GOV_SDID UNIQUE (SGID)
);
INSERT INTO gov(GID, Name, Address, TermBegin)
values(110, 'Bob', '123 Any St', '1-Jan-2009');
INSERT INTO STATE values(111, 'Virginia', 2000000, 110);
A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.
To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).
For example:
CREATE TABLE Vendor(
VendorNumber number(4) PRIMARY KEY,
Name varchar2(20),
Address varchar2(20),
City varchar2(15),
Street varchar2(2),
ZipCode varchar2(10),
Contact varchar2(16),
PhoneNumber varchar2(12),
Status varchar2(8),
StampDate date
);
CREATE TABLE Inventory(
Item varchar2(6) PRIMARY KEY,
Description varchar2(30),
CurrentQuantity number(4) NOT NULL,
VendorNumber number(2) REFERENCES Vendor(VendorNumber),
ReorderQuantity number(3) NOT NULL
);
A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.
To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.
CREATE TABLE Class(
ClassID varchar2(10) PRIMARY KEY,
Title varchar2(30),
Instructor varchar2(30),
Day varchar2(15),
Time varchar2(10)
);
CREATE TABLE Student(
StudentID varchar2(15) PRIMARY KEY,
Name varchar2(35),
Major varchar2(35),
ClassYear varchar2(10),
Status varchar2(10)
);
CREATE TABLE ClassStudentRelation(
StudentID varchar2(15) NOT NULL,
ClassID varchar2(14) NOT NULL,
FOREIGN KEY (StudentID) REFERENCES Student(StudentID),
FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
UNIQUE (StudentID, ClassID)
);
Casting int
to char
involves losing data and the compiler will probably warn you.
Extracting a particular byte from an int
sounds more reasonable and can be done like this:
number & 0x000000ff; /* first byte */
(number & 0x0000ff00) >> 8; /* second byte */
(number & 0x00ff0000) >> 16; /* third byte */
(number & 0xff000000) >> 24; /* fourth byte */
A solution that is viable for both Linux and Windows is to just get used to using console ffmpeg in your code. I stack up threads, write a simple thread controller class, then you can easily make use of what ever functionality of ffmpeg you want to use.
As an example, this contains sections use ffmpeg to create a thumbnail from a time that I specify.
In the thread controller you have something like
List<ThrdFfmpeg> threads = new List<ThrdFfmpeg>();
Which is the list of threads that you are running, I make use of a timer to Pole these threads, you can also set up an event if Pole'ing is not suitable for your application. In this case thw class Thrdffmpeg contains,
public class ThrdFfmpeg
{
public FfmpegStuff ffm { get; set; }
public Thread thrd { get; set; }
}
FFmpegStuff contains the various ffmpeg functionality, thrd is obviously the thread.
A property in FfmpegStuff is the class FilesToProcess, which is used to pass information to the called process, and receive information once the thread has stopped.
public class FileToProcess
{
public int videoID { get; set; }
public string fname { get; set; }
public int durationSeconds { get; set; }
public List<string> imgFiles { get; set; }
}
VideoID (I use a database) tells the threaded process which video to use taken from the database. fname is used in other parts of my functions that use FilesToProcess, but not used here. durationSeconds - is filled in by the threads that just collect video duration. imgFiles is used to return any thumbnails that were created.
I do not want to get bogged down in my code when the purpose of this is to encourage the use of ffmpeg in easily controlled threads.
Now we have our pieces we can add to our threads list, so in our controller we do something like,
AddThread()
{
ThrdFfmpeg thrd;
FileToProcess ftp;
foreach(FileToProcess ff in `dbhelper.GetFileNames(txtCategory.Text))`
{
//make a thread for each
ftp = new FileToProcess();
ftp = ff;
ftp.imgFiles = new List<string>();
thrd = new ThrdFfmpeg();
thrd.ffm = new FfmpegStuff();
thrd.ffm.filetoprocess = ftp;
thrd.thrd = new `System.Threading.Thread(thrd.ffm.CollectVideoLength);`
threads.Add(thrd);
}
if(timerNotStarted)
StartThreadTimer();
}
Now Pole'ing our threads becomes a simple task,
private void timerThreads_Tick(object sender, EventArgs e)
{
int runningCount = 0;
int finishedThreads = 0;
foreach(ThrdFfmpeg thrd in threads)
{
switch (thrd.thrd.ThreadState)
{
case System.Threading.ThreadState.Running:
++runningCount;
//Note that you can still view data progress here,
//but remember that you must use your safety checks
//here more than anywhere else in your code, make sure the data
//is readable and of the right sort, before you read it.
break;
case System.Threading.ThreadState.StopRequested:
break;
case System.Threading.ThreadState.SuspendRequested:
break;
case System.Threading.ThreadState.Background:
break;
case System.Threading.ThreadState.Unstarted:
//Any threads that have been added but not yet started, start now
thrd.thrd.Start();
++runningCount;
break;
case System.Threading.ThreadState.Stopped:
++finishedThreads;
//You can now safely read the results, in this case the
//data contained in FilesToProcess
//Such as
ThumbnailsReadyEvent( thrd.ffm );
break;
case System.Threading.ThreadState.WaitSleepJoin:
break;
case System.Threading.ThreadState.Suspended:
break;
case System.Threading.ThreadState.AbortRequested:
break;
case System.Threading.ThreadState.Aborted:
break;
default:
break;
}
}
if(flash)
{//just a simple indicator so that I can see
//that at least one thread is still running
lbThreadStatus.BackColor = Color.White;
flash = false;
}
else
{
lbThreadStatus.BackColor = this.BackColor;
flash = true;
}
if(finishedThreads >= threads.Count())
{
StopThreadTimer();
ShowSample();
MakeJoinedThumb();
}
}
Putting your own events onto into the controller class works well, but in video work, when my own code is not actually doing any of the video file processing, poling then invoking an event in the controlling class works just as well.
Using this method I have slowly built up just about every video and stills function I think I will ever use, all contained in the one class, and that class as a text file is useable on the Lunux and Windows version, with just a small number of pre-process directives.
A variation on the .agg() function; provides the ability to (1) persist type DataFrame, (2) apply averages, counts, summations, etc. and (3) enables groupby on multiple columns while maintaining legibility.
df.groupby(['att1', 'att2']).agg({'att1': "count", 'att3': "sum",'att4': 'mean'})
using your values...
df.groupby(['Name', 'Fruit']).agg({'Number': "sum"})
If this string is for presentation to the end user, you should use NSNumberFormatter
. This will add thousands separators, and will honor the localization settings for the user:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];
In the US, for example, that would create a string 10,000
, but in Germany, that would be 10.000
.
you can directly set boolean value equivalent to any string by System class and access it anywhere..
System.setProperty("n","false");
System.setProperty("y","true");
System.setProperty("yes","true");
System.setProperty("no","false");
System.out.println(Boolean.getBoolean("n")); //false
System.out.println(Boolean.getBoolean("y")); //true
System.out.println(Boolean.getBoolean("no")); //false
System.out.println(Boolean.getBoolean("yes")); //true
private router: Router
this.router.navigateByUrl(url)
It will redirect to any pages without data lost (even current page). Data will remain as is.
This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.
Here's the difference:
INSERT
creates a new row. I'm guessing that you really want to create a new row.UPDATE
changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.So this will probably do what you want:
$sql = "INSERT INTO `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :email, :telephone);
";
Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.
MySQL also supports an alternative syntax for INSERT:
$sql = "INSERT INTO `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
";
This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.
Iv'e fixed/improved Tomalak's answer with:
location.search
value instead of a url.Code:
function getSearchObject() {
if (location.search === "") return {};
var o = {},
nvPairs = location.search.substr(1).replace(/\+/g, " ").split("&");
nvPairs.forEach( function (pair) {
var e = pair.indexOf('=');
var n = decodeURIComponent(e < 0 ? pair : pair.substr(0,e)),
v = (e < 0 || e + 1 == pair.length)
? null :
decodeURIComponent(pair.substr(e + 1,pair.length - e));
if (!(n in o))
o[n] = v;
else if (o[n] instanceof Array)
o[n].push(v);
else
o[n] = [o[n] , v];
});
return o;
}
My answer is WRT python 2.6.2.
import commands
status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")
print output
I apologize for not providing the required parameters 'coz it's confidential.
As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.
This has worked for me:
HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
Problem is that while runtime generic type is erased so new E[10]
would be equivalent to new Object[10]
.
This would be dangerous because it would be possible to put in array other data than of E
type. That is why you need to explicitly say that type you want by either
E[]
array, or componentType
argiment.The Thread.Abort() method is (severely) deprecated.
Both Threads and Tasks should cooperate when being stopped, otherwise you run the risk of leaving the system in a unstable/undefined state.
If you do need to run a Process and kill it from the outside, the only safe option is to run it in a separate AppDomain.
This answer is about .net 3.5 and earlier.
Thread-abort handling has been improved since then, a.o. by changing the way finally blocks work.
But Thread.Abort is still a suspect solution that you should always try to avoid.
My favourite CSV parser is one built into .NET library. This is a hidden treasure inside Microsoft.VisualBasic namespace. Below is a sample code:
using Microsoft.VisualBasic.FileIO;
var path = @"C:\Person.csv"; // Habeeb, "Dubai Media City, Dubai"
using (TextFieldParser csvParser = new TextFieldParser(path))
{
csvParser.CommentTokens = new string[] { "#" };
csvParser.SetDelimiters(new string[] { "," });
csvParser.HasFieldsEnclosedInQuotes = true;
// Skip the row with the column names
csvParser.ReadLine();
while (!csvParser.EndOfData)
{
// Read current line fields, pointer moves to the next line.
string[] fields = csvParser.ReadFields();
string Name = fields[0];
string Address = fields[1];
}
}
Remember to add reference to Microsoft.VisualBasic
More details about the parser is given here: http://codeskaters.blogspot.ae/2015/11/c-easiest-csv-parser-built-in-net.html
You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.
There is an interesting difference between the two popular solutions above:
If you create the bare repository like this:
cd /outside_of_any_repo mkdir my_remote.git cd my_remote.git git init --bare
and then
cd /your_path/original_repo
git remote add origin /outside_of_any_repo/my_remote.git
git push --set-upstream origin master
Then git sets up the configuration in 'original_repo' with this relationship:
original_repo origin --> /outside_of_any_repo/my_remote.git/
with the latter as the upstream remote. And the upstream remote doesn't have any other remotes in its configuration.
However, if you do it the other way around:
(from in directory original_repo) cd .. git clone --bare original_repo /outside_of_any_repo/my_remote.git
then 'my_remote.git' winds up with its configuration having 'origin' pointing back to 'original_repo' as a remote, with a remote.origin.url equating to local directory path, which might not be appropriate if it is going to be moved to a server.
While that "remote" reference is easy to get rid of later if it isn't appropriate, 'original_repo' still has to be set up to point to 'my_remote.git' as an up-stream remote (or to wherever it is going to be shared from). So technically, you can arrive at the same result with a few more steps with approach #2. But #1 seems a more direct approach to creating a "central bare shared repo" originating from a local one, appropriate for moving to a server, with fewer steps involved. I think it depends on the role you want the remote repo to play. (And yes, this is in conflict with the documentation here.)
Caveat: I learned the above (at this writing in early August 2019) by doing a test on my local system with a real repo, and then doing a file-by-file comparison between the results. But! I am still learning, so there could be a more correct way. But my tests have helped me conclude that #1 is my currently-preferred method.
Check your References!
Be sure that you are consistently pointing to the same 3rd party libraries (don't just trust versions, look at the path) across your solutions projects.
For example, If you use iTextSharp v.1.00.101 in one project and you NuGet or reference iTextSharp v1.00.102 somewhere else you will get these types of runtime errors that somehow trickle up into your code.
I changed my reference to iTextSharp in all 3 projects to point to the same DLL and everything worked.
What are you doing: (I am using bytes instead of in for better reading)
You start with int *ap
and so on, so your (your computers) memory looks like this:
-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory --------
100: something <- here is *ap
101: 41 <- here starts a[]
102: 42
103: 43
104: 44
105: 45
106: something <- here waits x
lets take a look waht happens when (print short cut for ...print("$d", ...)
print a[0] -> 41 //no surprise
print a -> 101 // because a points to the start of the array
print *a -> 41 // again the first element of array
print a+1 -> guess? 102
print *(a+1) -> whats behind 102? 42 (we all love this number)
and so on, so a[0] is the same as *a, a[1] = *(a+1), ....
a[n] just reads easier.
now, what happens at line 9?
ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45
// warning! converting int to pointer!
-------------- your memory --------
100: 45 <- here is *ap now 45
x = *ap; // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang! // dont touch neighbours garden
So the "warning" is not just a warning it's a severe error.
ifdef $(HAVE_CLIENT) libtest_LIBS = \ $(top_builddir)/libclient.la else ifdef $(HAVE_SERVER) libtest_LIBS = \ $(top_builddir)/libserver.la else libtest_LIBS = endif endif
NOTE: DO NOT indent the if then it don't work!
It's important to have clear definitions of what terms mean. Unfortunately there appears to be multiple definitions of what static and dynamic arrays mean.
Static variables are variables defined using static memory allocation. This is a general concept independent of C/C++. In C/C++ we can create static variables with global, file, or local scope like this:
int x[10]; //static array with global scope
static int y[10]; //static array with file scope
foo() {
static int z[10]; //static array with local scope
Automatic variables are usually implemented using stack-based memory allocation. An automatic array can be created in C/C++ like this:
foo() {
int w[10]; //automatic array
What these arrays , x, y, z
, and w
have in common is that the size for each of them is fixed and is defined at compile time.
One of the reasons that it's important to understand the distinction between an automatic array and a static array is that static storage is usually implemented in the data section (or BSS section) of an object file and the compiler can use absolute addresses to access the arrays which is impossible with stack-based storage.
What's usually meant by a dynamic array is not one that is resizeable but one implemented using dynamic memory allocation with a fixed size determined at run-time. In C++ this is done using the new
operator.
foo() {
int *d = new int[n]; //dynamically allocated array with size n
But it's possible to create an automatic array with a fixes size defined at runtime using alloca
:
foo() {
int *s = (int*)alloca(n*sizeof(int))
For a true dynamic array one should use something like std::vector
in C++ (or a variable length array in C).
What was meant for the assignment in the OP's question? I think it's clear that what was wanted was not a static or automatic array but one that either used dynamic memory allocation using the new
operator or a non-fixed sized array using e.g. std::vector
.
You don't need to have static
in function definition
The /P
switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
Two ways I've used it... first:
SET /P variable=
When batch file reaches this point (when left blank) it will halt and wait for user input. Input then becomes variable.
And second:
SET /P variable=<%temp%\filename.txt
Will set variable to contents (the first line) of the txt file. This method won't work unless the /P
is included. Both tested on Windows 8.1 Pro, but it's the same on 7 and 10.