Start by adding a regular matInput to your template. Let's assume you're using the formControl directive from ReactiveFormsModule to track the value of the input.
Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values, and implement more advanced forms.
import { FormsModule, ReactiveFormsModule } from "@angular/forms"; //this to use ngModule
...
imports: [
BrowserModule,
AppRoutingModule,
HttpModule,
FormsModule,
RouterModule,
ReactiveFormsModule,
BrowserAnimationsModule,
MaterialModule],
The comp.lang.c FAQ deals with the question
"What's the correct declaration of main()?"in Question 11.12a.
This should work:
string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.
Edit: Apparently, if you supply the complete url to ParseQueryString
it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.
Kendo grid is good as well as Wijmo. I know Kendo comes with Angular bindings for their datasource and I think Wijmo has an Angular plugin. Neither are free though.
Actually the answer is yes. Here is an example how you can do this: http://html5doctor.com/introducing-web-sql-databases/
The bad thing is that it's with very limited support by the browsers.
More information here HTML5 IndexedDB, Web SQL Database and browser wars
PS: As @Christoph said Web SQL is no longer in active maintenance and the Web Applications Working Group does not intend to maintain it further so look here https://developer.mozilla.org/en-US/docs/IndexedDB.
EDIT
As @clentfort said, you can access SQLite database with client-side JavaScript by using SQL.js.
Try this:
// Hide the login modal
$('#login').modal('hide');
// Show the next modal after the fade effect is finished
setTimeout(function(){ $('#lost').modal('show'); }, 500);
This simple hack works for me.
You have to check if the argument is undefined:
function func(a, b) {
if (a === undefined) a = "default value";
if (b === undefined) b = "default value";
}
Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.
Use the -isEqualToString:
method to compare the value of two strings. Using the C ==
operator will simply compare the addresses of the objects.
if ([category isEqualToString:@"Some String"])
{
// Do stuff...
}
From dictionary.reference.com:
Computers. to analyze (a string of characters) in order to associate groups of characters with the syntactic units of the underlying grammar.
The context of the definition is the translation of program text or a language in the general sense into its component parts with respect to a defined grammar -- turning program text into code. In the context of a particular language keyword, though, it generally means to convert the string value of a fundamental data type into an internal representation of that data type. For example, the string "10" becomes the number (integer) 10.
This might be like resurrecting a dead horse. But just so it's out there, the reason why the answer to these types of questions to simply put dll's into the system32 folder is because that folder is in the os's system path.
It's actually best practice to provide the os with a path link.
With windows 10
env: django 2.1.7
view:
dict_objs[query_obj.id] = {'obj': query_obj, 'tag': str_tag}
return render(request, 'obj.html', {'dict_objs': dict_objs})
template:
{% for obj_id,dict_obj in dict_objs.items %}
<td>{{ dict_obj.obj.obj_name }}</td>
<td style="display:none">{{ obj_id }}</td>
<td>{{ forloop.counter }}</td>
<td>{{ dict_obj.obj.update_timestamp|date:"Y-m-d H:i:s"}}</td>
Use malloc
and free
only for allocating memory that is going to be managed by c-centric libraries and APIs. Use new
and delete
(and the []
variants) for everything that you control.
Others have given you the answer about appendChild.
Calling document.write()
on a page that is not open (e.g. has finished loading) first calls document.open()
which clears the entire content of the document (including the script calling document.write), so it's rarely a good idea to do that.
I had a similar problem, with a lot of help from the web and this post I made a small application, my target is VCD and SVCD and I don't delete the source but I reckon it will be fairly easy to adapt to your own needs.
It can convert 1 video and cut it or can convert all videos in a folder, rename them and put them in a subfolder /VCD
I also add a small interface, hope someone else find it useful!
I put the code and file in here btw: http://tequilaphp.wordpress.com/2010/08/27/learning-python-making-a-svcd-gui/
Of course it is an old post but just for people how will find it through search engine.
Another solution is to run it like this for IE9 and later
iexplore.exe" -noframemerging http://google.com
iexplore.exe" -noframemerging http://gmail.com
-noframemerging means run IE independently. For example it you want to run 2 browser and login as different username it will not work if you just run 2 IE. but with -noframemerging it will work. -noframemerging works for IE9 and later, for early versions like IE8 it is -nomerge
usually I create 1 but file like this run_ie.bat
"c:\Program Files (x86)\Internet Explorer\iexplore.exe" -noframemerging %1
and I create another bat file like this run_2_ie.bat
start run_ie.bat http://google.com
start run_ie.bat http://yahoo.com
None of the examples above create 8-bit (8bpp) bitmap images. Some software, such as image processing, only supports 8bpp. Unfortunately the MS .NET libraries do not have a solution. The PixelFormat.Format8bppIndexed format looks promising but after a lot of attempts I couldn't get it working.
To create a true 8-bit bitmap file you need to create the proper headers. Ultimately I found the Grayscale library solution for creating 8-bit bitmap (BMP) files. The code is very simple:
Image image = Image.FromFile("c:/path/to/image.jpg");
GrayBMP_File.CreateGrayBitmapFile(image, "c:/path/to/8bpp/image.bmp");
The code for this project is far from pretty but it works, with one little simple-to-fix problem. The author hard-coded the image resolution to 10x10. Image processing programs do not like this. The fix is open GrayBMP_File.cs (yeah, funky file naming, I know) and replace lines 50 and 51 with the code below. The example sets the resolution to 200x200 but you should change it to the proper number.
int resX = 200;
int resY = 200;
// horizontal resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resX * 100), 24);
// vertical resolution
Copy_to_Index(DIB_header, BitConverter.GetBytes(resY * 100), 28);
The solution is:
SSLContext sslContext = SSLContexts.custom()
.useTLS()
.build();
SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(
sslContext,
new String[]{"TLSv1", "TLSv1.1"},
null,
BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpClient = HttpClients.custom()
.setSSLSocketFactory(f)
.build();
This requires org.apache.httpcomponents.httpclient 4.3.x though.
import java.io.*;
import java.net.*;
public class ConvertURLToFileName{
public static void main(String[] args)throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the URL : ");
String str = in.readLine();
try{
URL url = new URL(str);
System.out.println("File : "+ url.getFile());
System.out.println("Converting process Successfully");
}
catch (MalformedURLException me){
System.out.println("Converting process error");
}
I hope this will help you.
Not quite an answer, but a long comment with nice formatting of code to the other (correct) answers. If you try the following, you will see that what you are getting are views of the original array, not copies, and that was not the case for the accepted answer in the question you link. Be aware of the possible side effects!
>>> x = np.arange(9.0)
>>> a,b,c = np.split(x, 3)
>>> a
array([ 0., 1., 2.])
>>> a[1] = 8
>>> a
array([ 0., 8., 2.])
>>> x
array([ 0., 8., 2., 3., 4., 5., 6., 7., 8.])
>>> def chunks(l, n):
... """ Yield successive n-sized chunks from l.
... """
... for i in xrange(0, len(l), n):
... yield l[i:i+n]
...
>>> l = range(9)
>>> a,b,c = chunks(l, 3)
>>> a
[0, 1, 2]
>>> a[1] = 8
>>> a
[0, 8, 2]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8]
Could anybody post a working solution for doing this in the terminal?
ANDROID_HOME
is usually a directory like .android
. Its where things like the Debug Key will be stored.
export ANDROID_HOME=~/.android
You can automate it for your login. Just add it to your .bash_profile
(below is from my OS X 10.8.5 machine):
$ cat ~/.bash_profile
# MacPorts Installer addition on 2012-07-19 at 20:21:05
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
# Android
export ANDROID_NDK_ROOT=/opt/android-ndk-r9
export ANDROID_SDK_ROOT=/opt/android-sdk
export JAVA_HOME=`/usr/libexec/java_home`
export ANDROID_HOME=~/.android
export PATH="$ANDROID_SDK_ROOT/tools/":"$ANDROID_SDK_ROOT/platform-tools/":"$PATH"
According to David Turner on the NDK Mailing List, both ANDROID_NDK_ROOT
and ANDROID_SDK_ROOT
need to be set because other tools depend on those values (see Recommended NDK Directory?).
After modifying ~/.bash_profile
, then perform the following (or logoff and back on):
source ~/.bash_profile
I think I found what you are looking for since I was also looking for it.
You have to follow Pawel's steps and then go to the key that is "Cookie". This will open a submenu with all the cookies and it specifies their name, value, domain, etc...
Respectively the values are: Key, Value, Expiration Date, Domain, Path.
This shows all the keys for this domain.
So again to get there:
I had the same problem adn did not want this to be set globally, so I used the same TrustManager and SSLContext code as above, I just changed the Client to be created with special properties
ClientConfig config = new DefaultClientConfig();
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
new HostnameVerifier() {
@Override
public boolean verify( String s, SSLSession sslSession ) {
// whatever your matching policy states
}
}
));
Client client = Client.create(config);
The issue pointed in the comment is valid, so here is a different revision that's immune to that:
function show_alert() {
if(!confirm("Do you really want to do this?")) {
return false;
}
this.form.submit();
}
You can change the code by using class definition for the i
element:
<a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
Then you can switch the classes rapresenting the plus/minus state using toggleClass
with multiple classes:
$('#category-tabs li a').click(function(){
$(this).next('ul').slideToggle('500');
$(this).find('i').toggleClass('fa-plus-circle fa-minus-circle');
});
To align one flex child to the right set it withmargin-left: auto;
From the flex spec:
One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.
.wrap div:last-child {
margin-left: auto;
}
.wrap {_x000D_
display: flex;_x000D_
background: #ccc;_x000D_
width: 100%;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
background: #ccc;_x000D_
margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
.result div {_x000D_
float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>
_x000D_
Note:
You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1
) which would push the last item all the way to the right. (Demo)
The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.
.wrap {_x000D_
display: flex;_x000D_
background: #ccc;_x000D_
width: 100%;_x000D_
justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
flex: 1;_x000D_
}_x000D_
.result {_x000D_
background: #ccc;_x000D_
margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
content: '';_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
.result div {_x000D_
float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
<div>One</div>_x000D_
<div>Two</div>_x000D_
<div>Three</div>_x000D_
</div>
_x000D_
You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.
In the Controller, you can use the javax.json to convert and manipulate this.
Download and add the .jar to the project libs and import the JsonObject.
To create an json object, you can use
JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();
To read it from String, you can use
JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();
On ubuntu (version 18), some application support java 8 and do not support java 11. If this is the case , you can switch to java 8 by following instruction on below topic : https://askubuntu.com/questions/1133216/downgrading-java-11-to-java-8
just add onclick handler for anchor tag
onclick="this.parentNode.style.display = 'none'"
or change onclick handler for img tag
onclick="this.parentNode.parentNode.style.display = 'none'"
swift enforces you to initialise every member var before it is ever/might ever be used. Since it can't be sure what happens when it is supers turn, it errors out: better safe than sorry
Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:
subtractDates: function(date1, date2) {
return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
return moment().subtract(dateSince).milliseconds();
},
This answer is correct but has a problem: fields not defined. If you have more then one field, you can not recognize which one has error.
with this change you can display field name:
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ field.label }}</strong><span>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
I would advise against restricting the SecurityProtocol to TLS 1.1.
The recommended solution is to use
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls
Another option is add the following Registry key:
Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319
Value: SchUseStrongCrypto
It is worth noting that .NET 4.6 will use the correct protocol by default and does not require either solution.
Building on some of the answers here, but using some simple math for a smooth transition using a sine curve:
scrollTo(element, from, to, duration, currentTime) {
if (from <= 0) { from = 0;}
if (to <= 0) { to = 0;}
if (currentTime>=duration) return;
let delta = to-from;
let progress = currentTime / duration * Math.PI / 2;
let position = delta * (Math.sin(progress));
setTimeout(() => {
element.scrollTop = from + position;
this.scrollTo(element, from, to, duration, currentTime + 10);
}, 10);
}
Usage:
// Smoothly scroll from current position to new position in 1/2 second.
scrollTo(element, element.scrollTop, element.scrollTop + 400, 500, 0);
PS. take note of ES6 style
Use ExitCode if your main has a void return signature, otherwise you need to "set" it by the value you return.
If the Main method returns void, you can use this property to set the exit code that will be returned to the calling environment. If Main does not return void, this property is ignored. The initial value of this property is zero.
With sed -e '1,N d; M q'
you'll print lines N+1 through M. This is probably a bit better then grep -C
as it doesn't try to match lines to a pattern.
This looks a little better than your previous version but get rid of that .Activate on that line and see if you still get that error.
Dim sh1 As Worksheet
set sh1 = Workbooks.Add(filenum(lngPosition) & ".csv")
Creates a worksheet object. Not until you create that object do you want to start working with it. Once you have that object you can do the following:
sh1.Range("A69").Paste
sh1.Range("A69").Select
The sh1. explicitely tells Excel which object you are saying to work with... otherwise if you start selecting other worksheets while this code is running you could wind up pasting data to the wrong place.
Call setListAdapter()
again. This time with an empty ArrayList.
Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.
for those used to php:
//add this function
function foreach(arr, func){
for(var i in arr){
func(i, arr[i]);
}
}
usage:
foreach(myArray, function(i, v){
//run code here
});
similar to php version:
foreach(myArray as i=>v){
//run code here
}
In last 3 months, I have tried RadRails, Netbeans and RubyMine and finally settled on RubyMine not so much for features but for responsiveness and stability reasons.
In terms of features, RubyMine has slightly better code completion
, debugging
and code navigation
, but only ruby beginners(like myself) need them most. Relying on code completion and code navigation is anti-ruby/rails
, as ruby/rails names are supposed to be natural and each line of code needs to be in its convention determined location.
I second Dave's idea. I'm not always fond of pivot tables, but in this case they are pretty straightforward to use.
Here are my results:
It was so simple to create it that I have even recorded a macro in case you need to do this with VBA:
Sub Macro2()
'
' Macro2 Macro
'
'
Range("Table1[[#All],[DATA]]").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Table1", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination _
:="Sheet3!R3C7", TableName:="PivotTable4", DefaultVersion:= _
xlPivotTableVersion14
Sheets("Sheet3").Select
Cells(3, 7).Select
With ActiveSheet.PivotTables("PivotTable4").PivotFields("DATA")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables( _
"PivotTable4").PivotFields("DATA"), "Count of DATA", xlCount
End Sub
long
type in Python 2.x uses arbitrary precision arithmetic and has no such thing as maximum possible value. It is limited by the available memory. Python 3.x has no special type for values that cannot be represented by the native machine integer — everything is int
and conversion is handled behind the scenes.
The answer was given already by either Sivasubramaniam Arunachalam or ch3ka.
I am just adding a performances view of the answer.
dicttest={}
dicttest['ligne1']={'ligne1.1':'test','ligne1.2':'test8'}
%timeit dicttest['ligne1']['ligne1.1']
%timeit dicttest.get('ligne1').get('ligne1.1')
gives us :
112 ns ± 29.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
235 ns ± 9.82 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Cheap and nasty solution.. Use the ugly #! style.
To set it:
window.location.hash = '#!' + id;
To read it:
id = window.location.hash.replace(/^#!/, '');
Since it doesn't match and anchor or id in the page, it won't jump.
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
If you're a Tidyverse kind of person, here's the stringr solution:
R> library(stringr)
R> strings = c("TGAS_1121", "MGAS_1432", "ATGAS_1121")
R> strings %>% str_replace(".*_", "_")
[1] "_1121" "_1432" "_1121"
# Or:
R> strings %>% str_replace("^[A-Z]*", "")
[1] "_1121" "_1432" "_1121"
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
I don't know how it works with WingIDE, but for using PyLint with Geany, I set my external command to:
PYTHONPATH=${PYTHONPATH}:$(dirname %d) pylint --output-format=parseable --reports=n "%f"
where %f is the filename, and %d is the path. Might be useful for someone :)
If we want that UILabel
should shrink and expand based on text size then storyboard with autolayout is best option. Below are the steps to achieve this
Put UILabel in view controller and place it wherever you want. Also put 0
for numberOfLines
property of UILabel
.
Give it Top, Leading and Trailing space pin constraint.
Update Frame
and click on Fix Misplacement
. Now this UILabel will shrink if text is less and expand if text is more.I adopted the answer from @Darkwaltz4 for its brevity and would like to share how I adapted the solution to situations where the array may contain different keys for each iteration like so:
Array[0] ...
['dob'] = '12/08/1986';
['some_key'] = 'some value';
Array[1] ...
['dob'] = '12/08/1986';
Array[2] ...
['dob'] = '12/08/1986';
['some_key'] = 'some other value';
and maintained a "master key" like so:
$master_key = array( 'dob' => ' ' , 'some_key' => ' ' );
array_merge would have executed the merge in the Array[1] iteration based on $master_key and produced ['some_key'] = '', an empty value, for that iteration. Hence, array_intersect_key was used to modify $master_key in each iterations like so:
foreach ($customer as $customer) {
$modified_key = array_intersect_key($master_key, $unordered_array);
$properOrderedArray = array_merge($modified_key, $customer);
}
You can only launch apps that have registered a URL scheme. Then just like you open the SMS app by using sms:, you'll be able to open the app using their URL scheme.
There is a very good example available in the docs called LaunchMe which demonstrates this.
LaunchMe sample code as of 6th Nov 2017.
Using the javascript engine that is shipped with Java 6:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Wow
{
public static void main(String[] args) throws Exception
{
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
engine.eval("print(encodeURIComponent('\"A\" B ± \"'))");
}
}
Output: %22A%22%20B%20%c2%b1%20%22
The case is different but it's closer to what you want.
I know its old post but still I want to contribute
Above will not work if you have data format like this
'YYYMMDD'
For example:
Dt
20151104
So I tried following in order to get the desired result.
select cast(Left('20151104', 4)||'-'||substring('20151104',5,2)||'-'||substring('20151104', 7,2) as date) from SYSIBM.SYSDUMMY1;
Additionally, If you want to run the query from MS SQL linked server to DB2(To display only 100 rows).
SELECT top 100 * from OPENQUERY([Linked_Server_Name],
'select cast(Left(''20151104'', 4)||''-''||substring(''20151104'',5,2)||''-''||substring(''20151104'', 7,2) as date) AS Dt
FROM SYSIBM.SYSDUMMY1')
Result after above query:
Dt
2015-11-04
Hope this helps for others.
This should work...
var displayDate = new Date().toLocaleDateString();
alert(displayDate);
But I suspect you are trying it on something else, for example:
var displayDate = Date.now.toLocaleDateString(); // No!
alert(displayDate);
It is not possible to declare global variables in SQL Server. Sql server has a concept of global variables, but they are system defined and can not be extended.
obviously you can do all kinds of tricks with the SQL you are sending - SqlCOmmand has such a variable replacement mechanism for example - BEFORE you send it to SqlServer, but that is about it.
You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:
1.) change type of ID to int
instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea
First option requires to change every table that has a reference to this table, BUT it's worth it.
Here's an example of how you'd use filter
within your AngularJS JavaScript (rather than in an HTML element).
In this example, we have an array of Country records, each containing a name and a 3-character ISO code.
We want to write a function which will search through this list for a record which matches a specific 3-character code.
Here's how we'd do it without using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
for (var i = 0; i < $scope.CountryList.length; i++) {
if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
return $scope.CountryList[i];
};
};
return null;
};
Yup, nothing wrong with that.
But here's how the same function would look, using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })
// If 'filter' didn't find any matching records, its result will be an array of 0 records.
if (matches.length == 0)
return null;
// Otherwise, it should've found just one matching record
return matches[0];
};
Much neater.
Remember that filter
returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.
Hope this helps.
To answer the non-reproducability aspect of the question - Firefox automatically imports intermediate certificates into its certificate store. So if you've previously visited a site which has used the same Intermediate Certificate using a correctly configured certificate chain then Firefox will store that Certificate so you will not see the problem when you visit a site that has an incorrectly configured chain using the same Intermediate certificate.
You can check this in Firefox's Certificate Manager (Options->Privacy&Security->View Certificates...) where you can see all stored certificates. Under the 'Security Device' Column you can check where a certificate has come from - automatically/manually imported certificates will appear as from 'Software Security Device' as opposed to the 'Builtin Object Token', which are the default set installed with Firefox. You can delete/Distrust any specific certificates and test again.
OneToOneField (one-to-one) realizes, in object orientation, the notion of composition, while ForeignKey (one-to-many) relates to agregation.
You can use any one way
NSString *string=[NSString stringWithFormat:@"%@",url1];
or
NSString *str=[url1 absoluteString];
NSLog(@"string :: %@",string);
string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
NSLog(@"str :: %@", str);
str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/RemoDuplicateMedia.app/loading_circle_animation.gif
I had this problem (colons in the target name) because I had -n
in my GREP_OPTIONS
environment variable. Apparently, this caused configure
to generate the Makefile
incorrectly.
Does the HTML to PDF conversion really need to occur server-side using PHP?
I just came across jsPDF, a client-side solution using HTML5/JavaScript. The MIT-licensed code is on GitHub, too.
You can use "accept" attribute as a filter in the file select box. Using "accept" help you filter input files base on their "suffix" or their "meme type"
1.Filter based on suffix: Here "accept" attribute just allow to select files with .jpeg extension.
<input type="file" accept=".jpeg" />
2.Filter based on "file type" Here "accept" attribute just allow to select file with "image/jpeg" type.
<input type="file" accept="image/jpeg" />
Important: We can change or delete the extension of a file, without changing the meme type. For example it is possible to have a file without extension, but the type of this file can be "image/jpeg". So this file can not pass the accept=".jpeg" filter. but it can pass accept="image/jpeg".
3.We can use * to select all kind of a file type. For example below code allow to select all kind of images. for example "image/png" or "image/jpeg" or ... . All of them are allowed.
<input type="file" accept="image/*" />
4.We can use cama ( , ) as an "or operator" in select attribute. For example to allow all kind of images or pdf files we can use this code:
<input type="file" accept="image/* , application/pdf" />
You can try Alasql JavaScript library which can work together with XLSX.js library for easy export of Angular.js data. This is an example of controller with exportData() function:
function myCtrl($scope) {
$scope.exportData = function () {
alasql('SELECT * INTO XLSX("john.xlsx",{headers:true}) FROM ?',[$scope.items]);
};
$scope.items = [{
name: "John Smith",
email: "[email protected]",
dob: "1985-10-10"
}, {
name: "Jane Smith",
email: "[email protected]",
dob: "1988-12-22"
}];
}
See full HTML and JavaScript code for this example in jsFiddle.
UPDATED Another example with coloring cells.
Also you need to include two libraries:
As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.
There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.
Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:
Using sed can also be elegant in this situation. Example (replace line with matched group "yyy" from line):
$ cat testfile
xxx yyy zzz
yyy xxx zzz
$ cat testfile | sed -r 's#^.*(yyy).*$#\1#g'
yyy
yyy
Relevant manual page: https://www.gnu.org/software/sed/manual/sed.html#Back_002dreferences-and-Subexpressions
There are different ways. If you just want to check if one list contains any element from the other list, you can do this..
not set(list1).isdisjoint(list2)
I believe using isdisjoint
is better than intersection
for Python 2.6 and above.
I would like to add recommendations from oracle trouble shooting article.
Exception in thread thread_name: java.lang.OutOfMemoryError: Java heap space
The detail message Java heap space indicates object could not be allocated in the Java heap. This error does not necessarily imply a memory leak
Possible causes:
Simple configuration issue, where the specified heap size is insufficient for the application.
Application is unintentionally holding references to objects, and this prevents the objects from being garbage collected.
Excessive use of finalizers.
One other potential source of this error arises with applications that make excessive use of finalizers. If a class has a finalize method, then objects of that type do not have their space reclaimed at garbage collection time
After garbage collection, the objects are queued for finalization, which occurs at a later time. finalizers are executed by a daemon thread that services the finalization queue. If the finalizer thread cannot keep up with the finalization queue, then the Java heap could fill up and this type of OutOfMemoryError exception would be thrown.
One scenario that can cause this situation is when an application creates high-priority threads that cause the finalization queue to increase at a rate that is faster than the rate at which the finalizer thread is servicing that queue.
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
Just FYI:
html should be table & width:100%. span should be margin: auto;
create a filter.js and you can make this as reusable
angular.module('yourmodule').filter('date', function($filter)
{
return function(input)
{
if(input == null){ return ""; }
var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
return _date.toUpperCase();
};
});
view
<span>{{ d.time | date }}</span>
or in controller
var filterdatetime = $filter('date')( yourdate );
A regular expression for words would give you the most control. You would want to carefully consider how to deal with words with dashes or apostrophes, like "I'm".
HTML :
Enter Your Text : <input type="text" id="text-filed" value="test">
Using JS :
var textFiled = document.getElementById("text-filed");
textFiled.addEventListener("focus", function() { this.select(); });
Using JQuery :
$("#text-filed").focus(function() { $(this).select(); } );
Using React JS :
In the respective component -
<input
type="text"
value="test"
onFocus={e => e.target.select()}
/>
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
If what you want is the total number of records in the table appended to each row you can do something like
SELECT *
FROM my_table
CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
FROM MY_TABLE)
You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html
Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.
I have a pinball prototype that also gave me much trouble in the same areas. These are all the steps I've taken to almost (but not yet entirely) solve these problems:
For fast moving objects:
Set the rigidbody's Interpolate to 'Interpolate' (this does not affect the actual physics simulation, but updates the rendering of the object properly - use this only on important objects from a rendering point of view, like the player, or a pinball, but not for projectiles)
Set Collision Detection to Continuous Dynamic
Attach the script DontGoThroughThings (https://www.auto.tuwien.ac.at/wordpress/?p=260) to your object. This script cleverly uses the Raycasting solution I posted in my other answer to pull back offending objects to before the collision points.
In Edit -> Project Settings -> Physics:
Set Min Penetration for Penalty to a very low value. I've set mine to 0.001
Set Solver Iteration Count to a higher value. I've set mine to 50, but you can probably do ok with much less.
All that is going to have a penalty in performace, but that's unavoidable. The defaults values are soft on performance but are not really intented for proper simulation of small and fast-moving objects.
Be aware that running
import os
os.system("tzutil /s \"Central Standard Time\"");
will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
which will only set in the current environment time (in Unix only)
Yes, PHP supports arrays as session variables. See this page for an example.
As for your second question: once you set the session variable, it will remain the same until you either change it or unset
it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.
You may have to use SizedBox() widget between your column's children. Hope that'll be usefull
If you really want to be sure of orders, use "Row_Number()" and compare next record of current record (take a close look at "on" clause)
T1.ID + 1 = T2.ID
You are basically joining next row with current row, without specifying "min" or doing "top". If you have a small number of records, other solutions by "Dems" or "Quassanoi" will work fine.
with T2 as (
select ID = ROW_NUMBER() over (order by rowInt),
rowInt, Value
from myTable
)
select T1.RowInt, T1.Value, Diff = IsNull(T2.Value, 0) - T1.Value
from ( SELECT ID = ROW_NUMBER() over (order by rowInt), *
FROM myTable ) T1
left join T2 on T1.ID + 1 = T2.ID
ORDER BY T1.ID
You're not actually using promises here. Parse lets you use callbacks or promises; your choice.
To use promises, do the following:
query.find().then(function() {
console.log("success!");
}, function() {
console.log("error");
});
Now, to execute stuff after the promise is complete, you can just execute it inside the promise callback inside the then()
call. So far this would be exactly the same as regular callbacks.
To actually make good use of promises is when you chain them, like this:
query.find().then(function() {
console.log("success!");
return new Parse.Query(Obj).get("sOmE_oBjEcT");
}, function() {
console.log("error");
}).then(function() {
console.log("success on second callback!");
}, function() {
console.log("error on second callback");
});
Use the requests library, pretty print the results so you can better locate the keys/values you want to extract, and then use nested for loops to parse the data. In the example I extract step by step driving directions.
import json, requests, pprint
url = 'http://maps.googleapis.com/maps/api/directions/json?'
params = dict(
origin='Chicago,IL',
destination='Los+Angeles,CA',
waypoints='Joplin,MO|Oklahoma+City,OK',
sensor='false'
)
data = requests.get(url=url, params=params)
binary = data.content
output = json.loads(binary)
# test to see if the request was valid
#print output['status']
# output all of the results
#pprint.pprint(output)
# step-by-step directions
for route in output['routes']:
for leg in route['legs']:
for step in leg['steps']:
print step['html_instructions']
If you have to load the data asynchronously prior to scrolling down, here's the possible solution:
tableView.alpha = 0 // We want animation!
lastMessageShown = false // This is ivar
viewModel.fetch { [unowned self] result in
self.tableView.reloadData()
if !self.lastMessageShown {
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
if self.rowCount > 0 {
self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: self.rowCount, inSection: 0), atScrollPosition: .Bottom, animated: false)
}
UIView.animateWithDuration(0.1) {
self.tableView.alpha = 1
self.lastMessageShown = true // Do it once
}
}
}
}
For zsh (newers mac os versions), you should use
real_var="holaaaa"
aux_var="real_var"
echo ${(P)aux_var}
holaaaa
Instead of "!"
You can get just the edition name by using the following steps.
I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.
So there are three different ways to do this:
Option A) Create a new session with the profile
dev = boto3.session.Session(profile_name='dev')
Option B) Change the profile of the default session in code
boto3.setup_default_session(profile_name='dev')
Option C) Change the profile of the default session with an environment variable
$ AWS_PROFILE=dev ipython
>>> import boto3
>>> s3dev = boto3.resource('s3')
The trick that worked for me was to change the writing-mode for the duration of the div-alignment.
.outer{ _x000D_
/* Limit height of outer div so there has to be a line-break*/_x000D_
height:100px;_x000D_
_x000D_
/* Tell the browser we are writing chinese. This makes everything that is text_x000D_
top-bottom then left to right. */_x000D_
writing-mode:vertical-lr;_x000D_
_x000D_
}_x000D_
_x000D_
.outer > div{_x000D_
/* float:left behaves like float:top because this block is beeing aligned top-bottom first _x000D_
*/_x000D_
float:left;_x000D_
width:40px; _x000D_
_x000D_
/* Switch back to normal writing mode. If you leave this out, everything inside the_x000D_
div will also be top-bottom. */_x000D_
writing-mode:horizontal-tb;_x000D_
_x000D_
}
_x000D_
<div class="outer">_x000D_
<div>one</div>_x000D_
<div>two</div>_x000D_
<div>three</div>_x000D_
<div>four</div>_x000D_
<div>one</div>_x000D_
<div>two</div>_x000D_
<div>three</div>_x000D_
<div>four</div>_x000D_
<div>one</div>_x000D_
<div>two</div>_x000D_
<div>three</div>_x000D_
<div>four</div>_x000D_
</div>
_x000D_
In your situation you got a reference to the missing symbols. But in some situations, ld will not provide error information.
If you want to expand the information provided by ld, just add the following parameters to your $(LDFLAGS)
-Wl,-V
It is a possible security risk, it has a different scope of execution, and is quite inefficient, as it creates an entirely new scripting environment for the execution of the code. See here for some more info: eval.
It is quite useful, though, and used with moderation can add a lot of good functionality.
in json everything is string between double quote ", so you need escape " if it happen in value (only in direct writing) use backslash \
and everything in json file wrapped in {} change your json to
{_x000D_
[_x000D_
{_x000D_
"id": "services.html",_x000D_
"img": "img/SolutionInnerbananer.jpg",_x000D_
"html": "<h2 class=\"fg-white\">AboutUs</h2><p class=\"fg-white\">developing and supporting complex IT solutions.Touching millions of lives world wide by bringing in innovative technology</p>"_x000D_
}_x000D_
]_x000D_
}
_x000D_
Select the constant, type
Ctrl + 1 (quick fix)
Select "Convert to static import." from the drop down.
"Quick fix" has options even though it is not an error.
git push origin amd_qlp_tester
will work for you. If you just type git push
, then the remote of the current branch is the default value.
Syntax of push looks like this - git push <remote> <branch>
. If you look at your remote in .git/config
file, you will see an entry [remote "origin"]
which specifies url of the repository. So, in the first part of command you will tell Git where to find repository for this project, and then you just specify a branch.
While SimpleXML provides a way to remove XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the DOM extension. dom_import_simplexml() will help you with converting your SimpleXMLElement
into a DOMElement
.
Just some example code (tested with PHP 5.2.5):
$data='<data>
<seg id="A1"/>
<seg id="A5"/>
<seg id="A12"/>
<seg id="A29"/>
<seg id="A30"/>
</data>';
$doc=new SimpleXMLElement($data);
foreach($doc->seg as $seg)
{
if($seg['id'] == 'A12') {
$dom=dom_import_simplexml($seg);
$dom->parentNode->removeChild($dom);
}
}
echo $doc->asXml();
outputs
<?xml version="1.0"?>
<data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data>
By the way: selecting specific nodes is much more simple when you use XPath (SimpleXMLElement->xpath):
$segs=$doc->xpath('//seq[@id="A12"]');
if (count($segs)>=1) {
$seg=$segs[0];
}
// same deletion procedure as above
2020 simple way :
git reset <commit_hash>
Commit hash of the last commit you want to keep.
Best solution you have ever see.
Convert django.db.models.Model instance and all related ForeignKey, ManyToManyField and @Property function fields into dict.
"""
Convert django.db.models.Model instance and all related ForeignKey, ManyToManyField and @property function fields into dict.
Usage:
class MyDjangoModel(... PrintableModel):
to_dict_fields = (...)
to_dict_exclude = (...)
...
a_dict = [inst.to_dict(fields=..., exclude=...) for inst in MyDjangoModel.objects.all()]
"""
import typing
import django.core.exceptions
import django.db.models
import django.forms.models
def get_decorators_dir(cls, exclude: typing.Optional[set]=None) -> set:
"""
Ref: https://stackoverflow.com/questions/4930414/how-can-i-introspect-properties-and-model-fields-in-django
:param exclude: set or None
:param cls:
:return: a set of decorators
"""
default_exclude = {"pk", "objects"}
if not exclude:
exclude = default_exclude
else:
exclude = exclude.union(default_exclude)
return set([name for name in dir(cls) if name not in exclude and isinstance(getattr(cls, name), property)])
class PrintableModel(django.db.models.Model):
class Meta:
abstract = True
def __repr__(self):
return str(self.to_dict())
def to_dict(self, fields: typing.Optional[typing.Iterable]=None, exclude: typing.Optional[typing.Iterable]=None):
opts = self._meta
data = {}
# support fields filters and excludes
if not fields:
fields = set()
else:
fields = set(fields)
default_fields = getattr(self, "to_dict_fields", set())
fields = fields.union(default_fields)
if not exclude:
exclude = set()
else:
exclude = set(exclude)
default_exclude = getattr(self, "to_dict_exclude", set())
exclude = exclude.union(default_exclude)
# support syntax "field__childField__..."
self_fields = set()
child_fields = dict()
if fields:
for i in fields:
splits = i.split("__")
if len(splits) == 1:
self_fields.add(splits[0])
else:
self_fields.add(splits[0])
field_name = splits[0]
child_fields.setdefault(field_name, set())
child_fields[field_name].add("__".join(splits[1:]))
self_exclude = set()
child_exclude = dict()
if exclude:
for i in exclude:
splits = i.split("__")
if len(splits) == 1:
self_exclude.add(splits[0])
else:
field_name = splits[0]
if field_name not in child_exclude:
child_exclude[field_name] = set()
child_exclude[field_name].add("__".join(splits[1:]))
for f in opts.concrete_fields + opts.many_to_many:
if self_fields and f.name not in self_fields:
continue
if self_exclude and f.name in self_exclude:
continue
if isinstance(f, django.db.models.ManyToManyField):
if self.pk is None:
data[f.name] = []
else:
result = []
m2m_inst = f.value_from_object(self)
for obj in m2m_inst:
if isinstance(PrintableModel, obj) and hasattr(obj, "to_dict"):
d = obj.to_dict(
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name),
)
else:
d = django.forms.models.model_to_dict(
obj,
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name)
)
result.append(d)
data[f.name] = result
elif isinstance(f, django.db.models.ForeignKey):
if self.pk is None:
data[f.name] = []
else:
data[f.name] = None
try:
foreign_inst = getattr(self, f.name)
except django.core.exceptions.ObjectDoesNotExist:
pass
else:
if isinstance(foreign_inst, PrintableModel) and hasattr(foreign_inst, "to_dict"):
data[f.name] = foreign_inst.to_dict(
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name)
)
elif foreign_inst is not None:
data[f.name] = django.forms.models.model_to_dict(
foreign_inst,
fields=child_fields.get(f.name),
exclude=child_exclude.get(f.name),
)
elif isinstance(f, (django.db.models.DateTimeField, django.db.models.DateField)):
v = f.value_from_object(self)
if v is not None:
data[f.name] = v.isoformat()
else:
data[f.name] = None
else:
data[f.name] = f.value_from_object(self)
# support @property decorator functions
decorator_names = get_decorators_dir(self.__class__)
for name in decorator_names:
if self_fields and name not in self_fields:
continue
if self_exclude and name in self_exclude:
continue
value = getattr(self, name)
if isinstance(value, PrintableModel) and hasattr(value, "to_dict"):
data[name] = value.to_dict(
fields=child_fields.get(name),
exclude=child_exclude.get(name)
)
elif hasattr(value, "_meta"):
# make sure it is a instance of django.db.models.fields.Field
data[name] = django.forms.models.model_to_dict(
value,
fields=child_fields.get(name),
exclude=child_exclude.get(name),
)
elif isinstance(value, (set, )):
data[name] = list(value)
else:
data[name] = value
return data
https://gist.github.com/shuge/f543dc2094a3183f69488df2bfb51a52
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'¶m='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
You can try this...
<!--First Solution-->_x000D_
width: calc(100% - 100px);_x000D_
<!--Second Solution-->_x000D_
width: calc(100vh - 100px);
_x000D_
vw: viewport width
vh: viewport height
-The tag is Empty and it contains Attribute only. -The tag does not have 'Closing' tag.
So,
<img src='stackoverflow.png'>
<img src='stackoverflow.png' />
both are correct in HTML5 also.
WebDriverWait wait = new WebDriverWait(driver,5)
wait.until(ExpectedConditions.visibilityOf(element));
you can use this as some time before loading whole page code gets executed and throws and error. time is in second
Try to start the MySQL server:
mysql.server start
Try this configuration:
position to absolute
width to 100%
height to 100px
bottom to 10
background-color: blue
This can help actually move the div to the bottom. Just modify accordingly.
To trim specific char, you can use:
String s = s.replaceAll("^(,|\\s)*|(,|\\s)*$", "")
Here will strip leading and trailing space and comma.
Dude I know totally how you feel, but don't forget about inline styling. It is almost the super saiyan of the CSS specificity
So it should look something like this for you,
<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>
<span class="icon-bar" style="background-color: black !important;">
</span>
There is no anyway to preview pdf document in Android webview.If you want to preview base64 pdf. It requires to third-party library.
build.Gradle
compile 'com.github.barteksc:android-pdf-viewer:2.7.0'
dialog_pdf_viewer
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="@+id/dialog_pdf_viewer_close"
style="@style/ExitButtonImageViewStyle"
android:src="@drawable/popup_exit" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@color/white"
android:orientation="vertical">
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<View style="@style/HorizontalLine" />
<com.pozitron.commons.customviews.ButtonFont
android:id="@+id/dialog_pdf_viewer_button"
style="@style/ButtonPrimary2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:text="@string/agreed" />
</LinearLayout>
DailogPDFViewer.java
public class DialogPdfViewer extends Dialog {
PDFView pdfView;
byte[] decodedString;
public interface OnDialogPdfViewerListener {
void onAgreeClick(DialogPdfViewer dialogFullEula);
void onCloseClick(DialogPdfViewer dialogFullEula);
}
public DialogPdfViewer(Context context, String base64, final DialogPdfViewer.OnDialogPdfViewerListener onDialogPdfViewerListener) {
super(context);
setContentView(R.layout.dialog_pdf_viewer);
findViewById(R.id.dialog_pdf_viewer_close).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
}
});
findViewById(R.id.dialog_pdf_viewer_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onDialogPdfViewerListener.onAgreeClick(DialogPdfViewer.this);
}
});
decodedString = Base64.decode(base64.toString(), Base64.DEFAULT);
pdfView = ((PDFView) findViewById(R.id.pdfView));
pdfView.fromBytes(decodedString).load();
setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
onDialogPdfViewerListener.onCloseClick(DialogPdfViewer.this);
}
return true;
}
});
}
}
Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security
. Your JAVA_HOME should always be ../JAVA/JDK
.
With ’
you know for certain that the output will be correct, no matter what.
I wish '
would output the proper apostrophe and not the typewriter apostrophe.
elements is an array of DOM objects. You should do something like this
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('hover');
}
ie: enumerate the elements collection, and for each element inside the collection call the remove method
import java.util.Random;
public class passGen{
// Version 1.0
private static final String dCase = "abcdefghijklmnopqrstuvwxyz";
private static final String uCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String sChar = "!@#$%^&*";
private static final String intChar = "0123456789";
private static Random r = new Random();
private static StringBuilder pass = new StringBuilder();
public static void main (String[] args) {
System.out.println ("Generating pass...");
while (pass.length () != 16){
int rPick = r.nextInt(4);
if (rPick == 0){
int spot = r.nextInt(26);
pass.append(dCase.charAt(spot));
} else if (rPick == 1) {
int spot = r.nextInt(26);
pass.append(uCase.charAt(spot));
} else if (rPick == 2) {
int spot = r.nextInt(8);
pass.append(sChar.charAt(spot));
} else {
int spot = r.nextInt(10);
pass.append(intChar.charAt(spot));
}
}
System.out.println ("Generated Pass: " + pass.toString());
}
}
This just adds the password into the string and... yeah, it works well. Check it out... It is very simple; I wrote it.
Your string is not valid. Double quots cannot be inside double quotes. You should escape them:
"{\"TeamList\" : [{\"teamid\" : \"1\",\"teamname\" : \"Barcelona\"}]}"
or use single quotes and double quotes
'{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'
In my case, the correct menu path was:
File > Default settings > Project Interpreter
Instead of
InputStream fstream = this.getClass().getResourceAsStream("abc.txt");
use
InputStream fstream = this.getClass().getClassLoader().getResourceAsStream("abc.txt");
In this way it will look from the root, not from the path of the current invoking class
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
The best way I have found so far is to use React Context but to isolate it inside a high order provider component.
Use double to cast like
Math.ceil((double)value)
or like
Math.ceil((double)value1/(double)value2);
// Nice method's name, @Dan Tao
public static bool ContainsAny(this string value, params string[] params)
{
return params.Any(p => value.Compare(p) > 0);
// or
return params.Any(p => value.Contains(p));
}
Any
for any, All
for every
SHA1 is a one way hash. So you can not really revert it.
That's why applications use it to store the hash of the password and not the password itself.
Like every hash function SHA-1 maps a large input set (the keys) to a smaller target set (the hash values). Thus collisions can occur. This means that two values of the input set map to the same hash value.
Obviously the collision probability increases when the target set is getting smaller. But vice versa this also means that the collision probability decreases when the target set is getting larger and SHA-1's target set is 160 bit.
Jeff Preshing, wrote a very good blog about Hash Collision Probabilities that can help you to decide which hash algorithm to use. Thanks Jeff.
In his blog he shows a table that tells us the probability of collisions for a given input set.
As you can see the probability of a 32-bit hash is 1 in 2 if you have 77163 input values.
A simple java program will show us what his table shows:
public class Main {
public static void main(String[] args) {
char[] inputValue = new char[10];
Map<Integer, String> hashValues = new HashMap<Integer, String>();
int collisionCount = 0;
for (int i = 0; i < 77163; i++) {
String asString = nextValue(inputValue);
int hashCode = asString.hashCode();
String collisionString = hashValues.put(hashCode, asString);
if (collisionString != null) {
collisionCount++;
System.out.println("Collision: " + asString + " <-> " + collisionString);
}
}
System.out.println("Collision count: " + collisionCount);
}
private static String nextValue(char[] inputValue) {
nextValue(inputValue, 0);
int endIndex = 0;
for (int i = 0; i < inputValue.length; i++) {
if (inputValue[i] == 0) {
endIndex = i;
break;
}
}
return new String(inputValue, 0, endIndex);
}
private static void nextValue(char[] inputValue, int index) {
boolean increaseNextIndex = inputValue[index] == 'z';
if (inputValue[index] == 0 || increaseNextIndex) {
inputValue[index] = 'A';
} else {
inputValue[index] += 1;
}
if (increaseNextIndex) {
nextValue(inputValue, index + 1);
}
}
}
My output end with:
Collision: RvV <-> SWV
Collision: SvV <-> TWV
Collision: TvV <-> UWV
Collision: UvV <-> VWV
Collision: VvV <-> WWV
Collision: WvV <-> XWV
Collision count: 35135
It produced 35135 collsions and that's the nearly the half of 77163. And if I ran the program with 30084 input values the collision count is 13606. This is not exactly 1 in 10, but it is only a probability and the example program is not perfect, because it only uses the ascii chars between A
and z
.
Let's take the last reported collision and check
System.out.println("VvV".hashCode());
System.out.println("WWV".hashCode());
My output is
86390
86390
Conclusion:
If you have a SHA-1 value and you want to get the input value back you can try a brute force attack. This means that you have to generate all possible input values, hash them and compare them with the SHA-1 you have. But that will consume a lot of time and computing power. Some people created so called rainbow tables for some input sets. But these do only exist for some small input sets.
And remember that many input values map to a single target hash value. So even if you would know all mappings (which is impossible, because the input set is unbounded) you still can't say which input value it was.
The Extensive Examination of Data Structures Using C# article on MSDN states that there is also a difference in the collision resolution strategy:
The Hashtable class uses a technique referred to as rehashing.
Rehashing works as follows: there is a set of hash different functions, H1 ... Hn, and when inserting or retrieving an item from the hash table, initially the H1 hash function is used. If this leads to a collision, H2 is tried instead, and onwards up to Hn if needed.
The Dictionary uses a technique referred to as chaining.
With rehashing, in the event of a collision the hash is recomputed, and the new slot corresponding to a hash is tried. With chaining, however, a secondary data structure is utilized to hold any collisions. Specifically, each slot in the Dictionary has an array of elements that map to that bucket. In the event of a collision, the colliding element is prepended to the bucket's list.
Or if all borders have same style, just:
border:10px;
There's no easy way of doing this, other than doing something like class="lastCell" on the last td in each tr, and then setting your css up like this:
#table td {
border-right: 5px solid red
}
.lastCell {
border-right: none;
}
Use the overloads that take the controller name too...
return RedirectToAction("Index", "MyController");
and
@Html.ActionLink("Link Name","Index", "MyController", null, null)
A mask defines which bits you want to keep, and which bits you want to clear.
Masking is the act of applying a mask to a value. This is accomplished by doing:
Below is an example of extracting a subset of the bits in the value:
Mask: 00001111b
Value: 01010101b
Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:
Mask: 00001111b
Value: 01010101b
Result: 00000101b
Masking is implemented using AND, so in C we get:
uint8_t stuff(...) {
uint8_t mask = 0x0f; // 00001111b
uint8_t value = 0x55; // 01010101b
return mask & value;
}
Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &
, and >>
(shift right). This is how we can extract the four bytes from a 32-bit integer:
void more_stuff(uint32_t value) { // Example value: 0x01020304
uint32_t byte1 = (value >> 24); // 0x01020304 >> 24 is 0x01 so
// no masking is necessary
uint32_t byte2 = (value >> 16) & 0xff; // 0x01020304 >> 16 is 0x0102 so
// we must mask to get 0x02
uint32_t byte3 = (value >> 8) & 0xff; // 0x01020304 >> 8 is 0x010203 so
// we must mask to get 0x03
uint32_t byte4 = value & 0xff; // here we only mask, no shifting
// is necessary
...
}
Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:
uint32_t byte3 = (value & 0xff00) >> 8;
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
After adding files to the stage, you need to commit them with git commit -m "comment"
after git add .
. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>
.
You can try this:
Map<String,String> map = new HashMap<>();
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue();
Keep in mind, HashMap
does not guarantee the insertion order. Use a LinkedHashMap
to keep the order intact.
Eg:
Map<String,String> map = new LinkedHashMap<>();
map.put("Active","33");
map.put("Renewals Completed","3");
map.put("Application","15");
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
System.out.println(key);
System.out.println(value);
Output:
Active
33
The existing answers missed an option, so here's a complete list:
// 1. Explicitly declare the type
var arr: Criminal[] = [];
// 2. Via type assertion
var arr = <Criminal[]>[];
var arr = [] as Criminal[];
// 3. Using the Array constructor
var arr = new Array<Criminal>();
Explicitly specifying the type is the general solution for whenever type inference fails for a variable declaration.
The advantage of using a type assertion (sometimes called a cast, but it's not really a cast in TypeScript) works for any expression, so it can be used even when no variable is declared. There are two syntaxes for type assertions, but only the latter will work in combination with JSX if you care about that.
Using the Array constructor is something that will only help you in this specific use case, but which I personally find the most readable. However, there is a slight performance impact at runtime*. Also, if someone were crazy enough to redefine the Array constructor, the meaning could change.
It's a matter of personal preference, but I find the third option the most readable. In the vast majority of cases the mentioned downsides would be negligible and readability is the most important factor.
*: Fun fact; at the time of writing the performance difference was 60% in Chrome, while in Firefox there was no measurable performance difference.
Use the scrollTop
property of the frame's content to set the content's vertical scroll-offset to a specific number of pixels (like 100):
<iframe src="foo.html" onload="this.contentWindow.document.documentElement.scrollTop=100"></iframe>
Yet another option which worked in my case on Windows 10: Try uninstalling your previous installation, restart the system and run the installation again.
Make sure you don't start any programs before installing Anaconda. You will find the installation finishes without prompting any kind of errors.
Type in Anaconda in your Windows 10 Search bar. You will find Anaconda Prompt appear.
falsetru's solution is nice, but has a little bug:
Suppose original 'id' length was larger than 5 characters. When we then dump with the new 'id' (134 with only 3 characters) the length of the string being written from position 0 in file is shorter than the original length. Extra chars (such as '}') left in file from the original content.
I solved that by replacing the original file.
import json
import os
filename = 'data.json'
with open(filename, 'r') as f:
data = json.load(f)
data['id'] = 134 # <--- add `id` value.
os.remove(filename)
with open(filename, 'w') as f:
json.dump(data, f, indent=4)
By simply subtracting by char '0'(zero) a char (of digit '0' to '9') can be converted into int(0 to 9), e.g., '5'-'0' gives int 5.
String str = "123";
int a=str.charAt(1)-'0';
Because you say
struct arg_struct *args = (struct arg_struct *)args;
instead of
struct arg_struct *args = arguments;
Create a custom Windows Service.
I had some mission-critical tasks set up as scheduled console apps and found them difficult to maintain. I created a Windows Service with a 'heartbeat' that would check a schedule in my DB every couple of minutes. It's worked out really well.
Having said that, I still use scheduled console apps for most of my non-critical maintenance tasks. If it ain't broke, don't fix it.
For MySQL to get random record
SELECT name
FROM random AS r1 JOIN
(SELECT (RAND() *
(SELECT MAX(id)
FROM random)) AS id)
AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1
More detail http://jan.kneschke.de/projects/mysql/order-by-rand/
Are you trying to represent it with only one digit:
print("{:.1f}".format(number)) # Python3
print "%.1f" % number # Python2
or actually round off the other decimal places?
round(number,1)
or even round strictly down?
math.floor(number*10)/10
Try this:
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UCS-2BE');
}, $str);
In case it's UTF-16 based C/C++/Java/Json-style:
$str = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) {
return mb_convert_encoding(pack('H*', $match[1]), 'UTF-8', 'UTF-16BE');
}, $str);
Yep, the limit is set by the kernel; check out this thread on Stack Overflow for more details: Increasing the maximum number of tcp/ip connections in linux
Here is an example using a recursive directive: http://jsfiddle.net/n8dPm/ Taken from https://groups.google.com/forum/#!topic/angular/vswXTes_FtM
module.directive("tree", function($compile) {
return {
restrict: "E",
scope: {family: '='},
template:
'<p>{{ family.name }}</p>'+
'<ul>' +
'<li ng-repeat="child in family.children">' +
'<tree family="child"></tree>' +
'</li>' +
'</ul>',
compile: function(tElement, tAttr) {
var contents = tElement.contents().remove();
var compiledContents;
return function(scope, iElement, iAttr) {
if(!compiledContents) {
compiledContents = $compile(contents);
}
compiledContents(scope, function(clone, scope) {
iElement.append(clone);
});
};
}
};
});
Window > Show view > Server
or right click on the server in "Servers" view, select "Properties".You may want to follow the steps above before starting the server. Because server location section goes grayed-unreachable.
You can't add them directly, you have to make a new array and then copy each of the arrays into the new one. System.arraycopy is a method you can use to perform this copy.
int[] array1and2 = new int[array1.length + array2.length];
System.arraycopy(array1, 0, array1and2, 0, array1.length);
System.arraycopy(array2, 0, array1and2, array1.length, array2.length);
This will work regardless of the size of array1 and array2.
You could use a print stylesheet, but this will affect all print functions.
You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print()
, then after that remove it.
I usually add separate safe pipe reusable component as following
# Add Safe Pipe
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
public transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}
# then create shared pipe module as following
import { NgModule } from '@angular/core';
import { SafePipe } from './safe.pipe';
@NgModule({
declarations: [
SafePipe
],
exports: [
SafePipe
]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module
@NgModule({
declarations: [],
imports: [
SharedPipesModule,
],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
<iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>
Maybe just another thing about LEA instruction. You can also use LEA for fast multiplying registers by 3, 5 or 9.
LEA EAX, [EAX * 2 + EAX] ;EAX = EAX * 3
LEA EAX, [EAX * 4 + EAX] ;EAX = EAX * 5
LEA EAX, [EAX * 8 + EAX] ;EAX = EAX * 9
Here is some C code that produces the above mentioned error:
int main(int argc, char **argv) {
exit(1);
}
Compiled like this on Fedora 17 Linux 64 bit with gcc:
el@defiant ~/foo2 $ gcc -o n n2.c
n2.c: In function ‘main’:
n2.c:2:3: warning: incompatible implicit declaration of built-in
function ‘exit’ [enabled by default]
el@defiant ~/foo2 $ ./n
el@defiant ~/foo2 $
To make the warning go away, add this declaration to the top of the file:
#include <stdlib.h>
Use logcat tool with -d
or -f
switch and exec() method.
Saving to a file on the host computer:
exec( "adb logcat -d > logcat.log" ) // logcat is written to logcat.log file on the host.
If you are just saving to a file on the device itself, you can use:
exec( "adb logcat -f logcat.log" ) // logcat is written to logcat.log file on the device.
It is simpler than I thought it would be.
To set the font size of the x-axis ticks:
x_ticks=['x tick 1','x tick 2','x tick 3']
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
To do it for the y-axis ticks:
y_ticks=['y tick 1','y tick 2','y tick 3']
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)
The arguments rotation
and fontsize
can easily control what I was after.
Reference: http://matplotlib.org/api/axes_api.html
One thing to consider is what NOT to set. Make certain your child controls, especially EditText controls, do not have the RequestFocus property set. This may be one of the last interpreted properties on the layout and it will override gravity settings on its parents (the layout or ScrollView).
You don't need HttpServletResponse to set a header on the response. You can do it using javax.ws.rs.core.Response. Just make your method to return Response instead of entity:
return Response.ok(entity).header("Content-Disposition", "attachment; filename=\"" + fileName + "\"").build()
If you still want to use HttpServletResponse you can get it either injected to one of the class fields, or using property, or to method parameter:
@Path("/resource")
class MyResource {
// one way to get HttpServletResponse
@Context
private HttpServletResponse anotherServletResponse;
// another way
Response myMethod(@Context HttpServletResponse servletResponse) {
// ... code
}
}
use your code within
<script type="text/javascript">
function window.onload()
{
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged
event:
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
// Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
// To work around this, we create the binding once we get the viewmodel through the datacontext.
var newViewModel = e.NewValue as MyViewModel;
var executablePathBinding = new Binding
{
Source = newViewModel,
Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
};
BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}
We have also had cases were we just saved the DataContext
to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext
around, I think it would be nice to also call:
BindingOperations.ClearBinding(myText, TextBlock.TextProperty);
to clear the binding of the old viewmodel (e.oldValue
in the event handler).
Add angular cookie lib : angular-cookies.js
You can use $cookies or $cookieStore parameter to the respective controller
Main controller add this inject 'ngCookies':
angular.module("myApp", ['ngCookies']);
Use Cookies in your controller like this way:
app.controller('checkoutCtrl', function ($scope, $rootScope, $http, $state, $cookies) {
//store cookies
$cookies.putObject('final_total_price', $rootScope.fn_pro_per);
//Get cookies
$cookies.getObject('final_total_price'); }
OpenSSL command line app does not display any characters when you are entering your password. Just type it then press enter and you will see that it is working.
You can also use openssl pkcs12 -export -inkey mykey.key -in developer_identity.pem -out iphone_dev.p12 -password pass:YourPassword
to pass the password YourPassword
from command line. Please take a look at section Pass Phrase Options in OpenSSL manual for more information.
In reply to Dimitrys answer but using Ajax.BeginForm
the following works at least with MVC >5 (4 not tested).
write a model as shown in the other answers,
In the "parent view" you will probably use a table to show the data.
Model should be an ienumerable. I assume, the model has an id
-property. Howeverm below the template, a placeholder for the modal and corresponding javascript
<table>
@foreach (var item in Model)
{
<tr> <td id="[email protected]">
@Html.Partial("dataRowView", item)
</td> </tr>
}
</table>
<div class="modal fade" id="editor-container" tabindex="-1"
role="dialog" aria-labelledby="editor-title">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content" id="editor-content-container"></div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('.editor-container').click(function () {
var url = "/area/controller/MyEditAction";
var id = $(this).attr('data-id');
$.get(url + '/' + id, function (data) {
$('#editor-content-container').html(data);
$('#editor-container').modal('show');
});
});
});
function success(data,status,xhr) {
$('#editor-container').modal('hide');
$('#editor-content-container').html("");
}
function failure(xhr,status,error) {
$('#editor-content-container').html(xhr.responseText);
$('#editor-container').modal('show');
}
</script>
note the "editor-success-id" in data table rows.
The dataRowView
is a partial containing the presentation of an model's item.
@model ModelView
@{
var item = Model;
}
<div class="row">
// some data
<button type="button" class="btn btn-danger editor-container" data-id="@item.Id">Edit</button>
</div>
Write the partial view that is called by clicking on row's button (via JS $('.editor-container').click(function () ...
).
@model Model
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="editor-title">Title</h4>
</div>
@using (Ajax.BeginForm("MyEditAction", "Controller", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "editor-success-" + @Model.Id,
OnSuccess = "success",
OnFailure = "failure",
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Id)
<div class="modal-body">
<div class="form-horizontal">
// Models input fields
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
}
This is where magic happens: in AjaxOptions
, UpdateTargetId will replace the data row after editing, onfailure and onsuccess will control the modal.
This is, the modal will only close when editing was successful and there have been no errors, otherwise the modal will be displayed after the ajax-posting to display error messages, e.g. the validation summary.
But how to get ajaxform to know if there is an error? This is the controller part, just change response.statuscode as below in step 5:
the corresponding controller action method for the partial edit modal
[HttpGet]
public async Task<ActionResult> EditPartData(Guid? id)
{
// Find the data row and return the edit form
Model input = await db.Models.FindAsync(id);
return PartialView("EditModel", input);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> MyEditAction([Bind(Include =
"Id,Fields,...")] ModelView input)
{
if (TryValidateModel(input))
{
// save changes, return new data row
// status code is something in 200-range
db.Entry(input).State = EntityState.Modified;
await db.SaveChangesAsync();
return PartialView("dataRowView", (ModelView)input);
}
// set the "error status code" that will redisplay the modal
Response.StatusCode = 400;
// and return the edit form, that will be displayed as a
// modal again - including the modelstate errors!
return PartialView("EditModel", (Model)input);
}
This way, if an error occurs while editing Model data in a modal window, the error will be displayed in the modal with validationsummary methods of MVC; but if changes were committed successfully, the modified data table will be displayed and the modal window disappears.
Note: you get ajaxoptions working, you need to tell your bundles configuration to bind jquery.unobtrusive-ajax.js
(may be installed by NuGet):
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
Namespacing. JavaScript's scopes are function-level.
ThisWorkbook.Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "XYZ"
(when you add a worksheet, anyway it'll be the active sheet)
I fixed this (for development) with a simple nginx proxy...
# /etc/nginx/sites-enabled/default
server {
listen 80;
root /path/to/Development/dir;
index index.html;
# from your example
location /search {
proxy_pass http://api.master18.tiket.com;
}
}
In case someone wanted an example using variables...
#!/bin/bash
# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"
if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi
In my case I was using MySql Server version: 8.0.22
I had to add
bind-address = 0.0.0.0
and change this line to be
mysqlx-bind-address = 0.0.0.0
in file at /etc/mysql/mysql.conf.d
then restart MySQL by running
sudo service mysql restart
In your invoke web request just use the parameter -UseBasicParsing
e.g. in your script (line 2) you should use:
$rss = Invoke-WebRequest -UseBasicParsing
According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.
Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.
android:text="Previous Line Next Line"
This will work.
I found we need to use noConflict sometimes:
jQuery.noConflict()(function ($) { // this was missing for me
$(document).ready(function() {
other code here....
});
});
From the docs:
Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case,
$
is just an alias for jQuery, so all functionality is available without using$
. If you need to use another JavaScript library alongside jQuery, return control of$
back to the other library with a call to$.noConflict()
. Old references of$
are saved during jQuery initialization;noConflict()
simply restores them.
You can make auto increment in SQL Modeler. In column properties window Click : General then Tick the box of Auto Increment. After that the auto increment window will be enabled for you.
Try to disable ModSecurity from your cPanel. Log into your cPanel. Find the category "Security". There you can find ModSecurity link.Click on it and disable it for the domain you are facing the 403 error.
Some 403 errors can be solved by this method too. Go to the wordpress dashboard, settings>permalink and just click save.
Hope this helped. :)
Two steps works fine:
create table bu_x as (select a,b,c,d from x ) WITH no data;
insert into bu_x (a,b,c,d) select select a,b,c,d from x ;
Using -flatten made me completely mad because -flatten in combination with mogrify crop and resizing simply doesn't work. The official and for me only correct way is to "remove" the alpha channel.
-alpha remove -alpha off (not needed with JPG)
See documention: http://www.imagemagick.org/Usage/masking/#remove
You could use a classmethod
or staticmethod
class Paul(object):
elems = []
@classmethod
def addelem(cls, e):
cls.elems.append(e)
@staticmethod
def addelem2(e):
Paul.elems.append(e)
Paul.addelem(1)
Paul.addelem2(2)
print(Paul.elems)
classmethod
has advantage that it would work with sub classes, if you really wanted that functionality.
module is certainly best though.
There are some straightforward examples already, but I notice from how you've worded your question that you probably come from a PHP background, and you're expecting JavaScript to work the same way -- it does not. A PHP array
is very different from a JavaScript Array
.
In PHP, an associative array can do most of what a numerically-indexed array can (the array_*
functions work, you can count()
it, etc.) You simply create an array and start assigning to string-indexes instead of numeric.
In JavaScript, everything is an object (except for primitives: string, numeric, boolean), and arrays are a certain implementation that lets you have numeric indexes. Anything pushed to an array will effect its length
, and can be iterated over using Array methods (map
, forEach
, reduce
, filter
, find
, etc.) However, because everything is an object, you're always free to simply assign properties, because that's something you do to any object. Square-bracket notation is simply another way to access a property, so in your case:
array['Main'] = 'Main Page';
is actually equivalent to:
array.Main = 'Main Page';
From your description, my guess is that you want an 'associative array', but for JavaScript, this is a simple case of using an object as a hashmap. Also, I know it's an example, but avoid non-meaningful names that only describe the variable type (e.g. array
), and name based on what it should contain (e.g. pages
). Simple objects don't have many good direct ways to iterate, so often we'll turn then into arrays first using Object
methods (Object.keys
in this case -- there's also entries
and values
being added to some browsers right now) which we can loop.
// assigning values to corresponding keys
const pages = {
Main: 'Main page',
Guide: 'Guide page',
Articles: 'Articles page',
Forum: 'Forum board',
};
Object.keys(pages).forEach((page) => console.log(page));
You could try Conditional Formatting available in the tool menu "Format -> Conditional Formatting".
I understand that this is a response to an old post-
I like the If() function combined with Index()/Match():
=IF(B2>0,"x",INDEX($H$2:$I$9,MATCH(A2,$H$2:$H$9,0),2))
The if function compare what is in column b and if it is greater than 0, it returns x, if not it uses the array (table of information) identified by the Index() function and selected by Match() to return the value that a corresponds to.
The Index array has the absolute location set $H$2:$I$9
(the dollar signs) so that the place it points to will not change as the formula is copied. The row with the value that you want returned is identified by the Match() function. Match() has the added value of not needing a sorted list to look through that Vlookup() requires. Match() can find the value with a value: 1 less than, 0 exact, -1 greater than. I put a zero in after the absolute Match() array $H$2:$H$9
to find the exact match. For the column that value of the Index() array that one would like returned is entered. I entered a 2 because in my array the return value was in the second column. Below my index array looked like this:
32 1420
36 1650
40 1790
44 1860
55 2010
The value in your 'a' column to search for in the list is in the first column in my example and the corresponding value that is to be return is to the right. The look up/reference table can be on any tab in the work book - or even in another file. -Book2 is the file name, and Sheet2 is the 'other tab' name.
=IF(B2>0,"x",INDEX([Book2]Sheet2!$A$1:$B$8,MATCH(A2,[Book2]Sheet2!$A$1:$A$8,0),2))
If you do not want x return when the value of b is greater than zero delete the x for a 'blank'/null equivalent or maybe put a 0 - not sure what you would want there.
Below is beginning of the function with the x deleted.
=IF(B2>0,"",INDEX...
If you build packages from scratch:
Specifically, if you build bash
from source, install docs, including man pages, will fail (silently) without makeinfo
available.
You can do this using the splat operator:
some_func(*params)
This causes the function to receive each list item as a separate parameter. There's a description here: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists
$("#target").on({
hover: function(){
//do on mouse hover
},
click: function(){
//do on mouse click
}
});
Use CHAR
:
=Char(34)&"This is in quotes"&Char(34)
Should evaluate to:
"This is in quotes"
Use:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= TRUNC(SYSDATE) - 30
SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date
that is 30 days previous including the current time.
Depending on your needs, you could also look at using ADD_MONTHS:
SELECT *
FROM YOUR_TABLE
WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)
Does c# have its own version of the java "synchronized" keyword?
No. In C#, you explicitly lock
resources that you want to work on synchronously across asynchronous threads. lock
opens a block; it doesn't work on method level.
However, the underlying mechanism is similar since lock
works by invoking Monitor.Enter
(and subsequently Monitor.Exit
) on the runtime. Java works the same way, according to the Sun documentation.
just use the core https module with the https.request function. Example for a POST
request (GET
would be similar):
var https = require('https');
var options = {
host: 'www.google.com',
port: 443,
path: '/upload',
method: 'POST'
};
var req = https.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
It's useful to work with Deferred Object in this case, and return promise:
function readImage(inputElement) {
var deferred = $.Deferred();
var files = inputElement.get(0).files;
if (files && files[0]) {
var fr= new FileReader();
fr.onload = function(e) {
deferred.resolve(e.target.result);
};
fr.readAsDataURL( files[0] );
} else {
deferred.resolve(undefined);
}
return deferred.promise();
}
And above function could be used in this way:
var inputElement = $("input[name=file]");
readImage(inputElement).done(function(base64Data){
alert(base64Data);
});
Or in your case:
$(input).on('change',function(){
readImage($(this)).done(function(base64Data){ alert(base64Data); });
});
I changed the "debug" to "info" and it worked. Here is what I did:
Before:
log4j.rootLogger=debug, stdout, R
After:
log4j.rootLogger=info, stdout, R
Georg have already mentioned ES6 have Array.findIndex for this. And some other answers are workaround for ES5 using Array.some method.
One more elegant approach can be
var index;
for(index = yourArray.length; index-- > 0 && yourArray[index].prop2 !== "yutu";);
At the same time I will like to emphasize, Array.some may be implemented with binary or other efficient searching technique. So, it might perform better over for loop in some browser.
Here my answer :
<form onsubmit="event.preventDefault();searchOrder(event);">
...
</form>
<script>
const searchOrder = e => {
e.preventDefault();
const name = e.target.name.value;
renderSearching();
return false;
}
</script>
I add event.preventDefault();
on onsubmit
and it works.
There are multiple ways you can do this but I am not sure which one is the best practice. The first approach is you can append an iFrame in the dialog container on the fly with your given link:
$("#dialog").append($("<iframe />").attr("src", "your link")).dialog({dialogoptions});
Another would be to load the content of your external link into the dialog container using ajax.
$("#dialog").load("yourajaxhandleraddress.htm").dialog({dialogoptions});
Both works fine but depends on the external content.
You'll want something like this:
$("#next").click(function(){
var currentElement = currentElement.next();
$('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
return false;
});
I believe this should work, it's adopted from a scrollTop
function.
@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
text.set_fontsize('x-large')
plt.savefig('leg_example')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')
leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()
The above two methods produce the same output image:
Resurrecting another topic, but this may come in handy for some.
With a little bit of inspiration from https://pyformat.info you can build a method to get a Table of Content [TOC] style printout.
# Define parameters
Location = '10-10-10-10'
Revision = 1
District = 'Tower'
MyDate = 'May 16, 2012'
MyUser = 'LOD'
MyTime = '10:15'
# This is just one way to arrange the data
data = [
['Location: '+Location, 'Revision:'+str(Revision)],
['District: '+District, 'Date: '+MyDate],
['User: '+MyUser,'Time: '+MyTime]
]
# The 'Table of Content' [TOC] style print function
def print_table_line(key,val,space_char,val_loc):
# key: This would be the TOC item equivalent
# val: This would be the TOC page number equivalent
# space_char: This is the spacing character between key and val (often a dot for a TOC), must be >= 5
# val_loc: This is the location in the string where the first character of val would be located
val_loc = max(5,val_loc)
if (val_loc <= len(key)):
# if val_loc is within the space of key, truncate key and
cut_str = '{:.'+str(val_loc-4)+'}'
key = cut_str.format(key)+'...'+space_char
space_str = '{:'+space_char+'>'+str(val_loc-len(key)+len(str(val)))+'}'
print(key+space_str.format(str(val)))
# Examples
for d in data:
print_table_line(d[0],d[1],' ',30)
print('\n')
for d in data:
print_table_line(d[0],d[1],'_',25)
print('\n')
for d in data:
print_table_line(d[0],d[1],' ',20)
The resulting output is as follows:
Location: 10-10-10-10 Revision:1
District: Tower Date: May 16, 2012
User: LOD Time: 10:15
Location: 10-10-10-10____Revision:1
District: Tower__________Date: May 16, 2012
User: LOD________________Time: 10:15
Location: 10-10-... Revision:1
District: Tower Date: May 16, 2012
User: LOD Time: 10:15
The good news is a transaction in SQL Server can span multiple batches (each exec
is treated as a separate batch.)
You can wrap your EXEC
statements in a BEGIN TRANSACTION
and COMMIT
but you'll need to go a step further and rollback if any errors occur.
Ideally you'd want something like this:
BEGIN TRY
BEGIN TRANSACTION
exec( @sqlHeader)
exec(@sqlTotals)
exec(@sqlLine)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
END CATCH
The BEGIN TRANSACTION
and COMMIT
I believe you are already familiar with. The BEGIN TRY
and BEGIN CATCH
blocks are basically there to catch and handle any errors that occur. If any of your EXEC
statements raise an error, the code execution will jump to the CATCH
block.
Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.
Permanent:
UPDATE
MyTable
SET
MyColumn = UPPER(MyColumn)
Temporary:
SELECT
UPPER(MyColumn) AS MyColumn
FROM
MyTable
place the required dlls in folder and set the folder path in PATH environment variable. make sure updated environment PATH variable is reflected.
Here is my one-file/lightweight node.js static file web-server pet project with no-dependency that I believe is a quick and rich tool which its use is as easy as issuing this command on your Linux/Unix/macOS terminal (or termux on Android) when node.js (or nodejs-legacy
on Debian/Ubuntu) is installed:
curl pad.js.org | node
(different commands exist for Windows users on the documentation)
It supports different things that I believe can be found useful,
curl pad.js.org | node - -h
[sudo] npm install -g pad.js
and then use its installed version to have access to its options: pad -h
[sudo] docker run --restart=always -v /files:/files --name pad.js -d -p 9090:9090 quay.io/ebraminio/pad.js
The features described above are mostly documented on the main page of the tool http://pad.js.org which by some nice trick I used is also the place the tool source itself is also served from!
The tool source is on GitHub which welcomes your feedback, feature requests and ?s!
Adding to Mike McAllister's pretty-thorough answer...
Materialized views can only be set to refresh automatically through the database detecting changes when the view query is considered simple by the compiler. If it's considered too complex, it won't be able to set up what are essentially internal triggers to track changes in the source tables to only update the changed rows in the mview table.
When you create a materialized view, you'll find that Oracle creates both the mview and as a table with the same name, which can make things confusing.
You're trying to concatenate a string and an integer, which is incorrect.
Change print(numlist.pop(2)+" has been removed")
to any of these:
Explicit int
to str
conversion:
print(str(numlist.pop(2)) + " has been removed")
Use ,
instead of +
:
print(numlist.pop(2), "has been removed")
String formatting:
print("{} has been removed".format(numlist.pop(2)))
Put the query arguments in hidden input fields:
<form action="http://spufalcons.com/index.aspx">
<input type="hidden" name="tab" value="gymnastics" />
<input type="hidden" name="path" value="gym" />
<input type="submit" value="SPU Gymnastics"/>
</form>
This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.
From the source code:
It can be called either on the class (e.g.
C.f()
) or on an instance (e.g.C().f()
); the instance is ignored except for its class.
But not directly from inside the class while it is being defined.
But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.
You could try this:
- Open the Terminal application. It can be found in the Utilities directory inside the Applications directory.
- Type the following: echo 'export PATH=YOURPATHHERE:$PATH' >> ~/.profile, replacing "YOURPATHHERE" with the name of the directory you want to add. Make certain that you use ">>" instead of one ">".
- Hit Enter.
- Close the Terminal and reopen. Your new Terminal session should now use the new PATH.
With the deprecation of GCM and removal of its APIs, it appears that you could see MismatchSenderId if you try to use GCM after May 29, 2019. See the Google GCM and FCM FAQ for more details.
I know that I am late to the party, but I discovered a nice solution.
Here it is:
var myStr = myStr.replace(/[ ][ ]*/g, ' ');
I had this problem and none of the other answers solved it, although of course the other answers were correct.
In my case, it turned out that the /root
directory itself (not e.g. /root/.ssh
) had the wrong permissions. I needed:
chown root.root /root
chmod 700 /root
Of course, those permissions should be something like that (maybe chmod 770
) regardless. However, it specifically prevented sshd
from working, even though /root/.ssh
and /root/.ssh/authorized_keys
both had correct permissions and owners.
If you need to check whether the elements of one vector are in another, the best solution is ismember
as mentioned in the other answers.
ismember([15 17],primes(20))
However when you are dealing with floating point numbers, or just want to have close matches (+- 1000 is also possible), the best solution I found is the fairly efficient File Exchange Submission: ismemberf
It gives a very practical example:
[tf, loc]=ismember(0.3, 0:0.1:1) % returns false
[tf, loc]=ismemberf(0.3, 0:0.1:1) % returns true
Though the default tolerance should normally be sufficient, it gives you more flexibility
ismemberf(9.99, 0:10:100) % returns false
ismemberf(9.99, 0:10:100,'tol',0.05) % returns true