So, I've done some work on family tree software. I think the problem you're trying to solve is that you need to be able to walk the tree without getting in infinite loops - in other words, the tree needs to be acyclical.
However, it looks like you're asserting that there is only one path between a person and one of their ancestors. That will guarantee that there are no cycles, but is too strict. Biologically speaking, descendancy is a directed acyclic graph (DAG). The case you have is certainly a degenerate case, but that type of thing happens all the time on larger trees.
For example, if you look at the 2^n ancestors you have at generation n, if there was no overlap, then you'd have more ancestors in 1000 AD than there were people alive. So, there's got to be overlap.
However, you also do tend to get cycles that are invalid, just bad data. If you're traversing the tree, then cycles must be dealt with. You can do this in each individual algorithm, or on load. I did it on load.
Finding true cycles in a tree can be done in a few ways. The wrong way is to mark every ancestor from a given individual, and when traversing, if the person you're going to step to next is already marked, then cut the link. This will sever potentially accurate relationships. The correct way to do it is to start from each individual, and mark each ancestor with the path to that individual. If the new path contains the current path as a subpath, then it's a cycle, and should be broken. You can store paths as vector<bool> (MFMF, MFFFMF, etc.) which makes the comparison and storage very fast.
There are a few other ways to detect cycles, such as sending out two iterators and seeing if they ever collide with the subset test, but I ended up using the local storage method.
Also note that you don't need to actually sever the link, you can just change it from a normal link to a 'weak' link, which isn't followed by some of your algorithms. You will also want to take care when choosing which link to mark as weak; sometimes you can figure out where the cycle should be broken by looking at birthdate information, but often you can't figure out anything because so much data is missing.
Loop invariant is a mathematical formula such as (x=y+1)
. In that example, x
and y
represent two variables in a loop. Considering the changing behavior of those variables throughout the execution of the code, it is almost impossible to test all possible to x
and y
values and see if they produce any bug. Lets say x
is an integer. Integer can hold 32 bit space in the memory. If that number exceeds, buffer overflow occurs. So we need to be sure that throughout the execution of the code, it never exceeds that space. for that, we need to understand a general formula that shows the relationship between variables.
After all, we just try to understand the behavior of the program.
There is a:not selector in css3. Use :not() with :last-child inside to select all children except last one. For example, to select all li in ul except last li, use following code.
ul li:not(:last-child){ }
I also had this problem. I used information from link, mentioned above, and found quick solution. If you have different schema, lets say test, and create user utest, owner of schema test and among views in schema test you have view vTestView, based on tables from schema dbo, while selecting from it you'll get error mentioned above - no access to base objects. It was enough for me to execute statement
ALTER AUTHORIZATION ON test.vTestView TO dbo
;
which means that I change an ownership of vTextView from schema it belongs to (test) to database user dbo, owner of schema dbo. After that without any other permissions required user utest will be able to access data from test.vTestView
psql databasename < data_base_dump
That's the command you are looking for.
Beware: databasename
must be created before importing.
Have a look at the PostgreSQL Docs Chapter 23. Backup and Restore.
Its mid 2019 and I faced this error after a few years of developing with Django. Baffled me for an entire night! It wasn't allowed host (which should throw a 400), everything else checked out, finally did some error logging only to discover that some missing / or messed up static files manifest (after collectstatic) were screwing with the setup. Long story short, for those who are stumped AND SO HAPPEN ARE USING WHITENOISE OR THE DJANGO STATICFILE BACKEND WITH CACHE (manifest static files) , maybe this is for you.
Make sure you setup everything (as I did for the whitenoise backend...django backends read on nonetheless) http://whitenoise.evans.io/en/stable/django.html
If error code 500 still shoots you down, take note on your settings.STATICFILES_STORAGE.
Set it to either (for whitenoise backend with compression)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'
or (leave as django default)
STATICFILES_STORAGE = django.contrib.staticfiles.storage.StaticFilesStorage
All in all, THE PROBLEM seemed to come from the fact that this whitenoise cache + compression backend -->
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
or the django's own caching backend -->
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
...didnt quite work well for me, since my css was referencing some other sources which may be mixed up during collectstatic / backend caching. This issue is also potentially highlighted in http://whitenoise.evans.io/en/stable/django.html#storage-troubleshoot
After struggling myself with this I found a solution that works just replace the $ with jQueryjQuery.fancybox.close()
and I made it an inline script on an onClick. Going to check if i can call it from the parent
First off, md5 and sha1 have been proven to be vulnerable to collision attacks and can be rainbow tabled easily (when they see if you hash is the same in their database of common passwords).
There are currently two things that are secure enough for passwords that you can use.
The first is sha512. sha512 is a sub-version of SHA2. SHA2 has not yet been proven to be vulnerable to collision attacks and sha512 will generate a 512-bit hash. Here is an example of how to use sha512:
<?php
hash('sha512',$password);
The other option is called bcrypt. bcrypt is famous for its secure hashes. It's probably the most secure one out there and most customizable one too.
Before you want to start using bcrypt you need to check if your sever has it enabled, Enter this code:
<?php
if (defined("CRYPT_BLOWFISH") && CRYPT_BLOWFISH) {
echo "CRYPT_BLOWFISH is enabled!";
}else {
echo "CRYPT_BLOWFISH is not available";
}
If it returns that it is enabled then the next step is easy, All you need to do to bcrypt a password is (note: for more customizability you need to see this How do you use bcrypt for hashing passwords in PHP?):
crypt($password, $salt);
A salt is usually a random string that you add at the end of all your passwords when you hash them. Using a salt means if someone gets your database, they can not check the hashes for common passwords. Checking the database is called using a rainbow table. You should always use a salt when hashing!
Here are my proofs for the SHA1 and MD5 collision attack vulnerabilities:
http://www.schneier.com/blog/archives/2012/10/when_will_we_se.html, http://eprint.iacr.org/2010/413.pdf,
http://people.csail.mit.edu/yiqun/SHA1AttackProceedingVersion.pdf,
http://conf.isi.qut.edu.au/auscert/proceedings/2006/gauravaram06collision.pdf and
Understanding sha-1 collision weakness
I basically like Anders' approach as it is very general. Here's a version that puts the categorizer first (to match filter syntax) and uses a defaultdict (assumed imported).
def categorize(func, seq):
"""Return mapping from categories to lists
of categorized items.
"""
d = defaultdict(list)
for item in seq:
d[func(item)].append(item)
return d
Converting the date without specifying the current format can bring this error to you easily.
sdate <- "2015.10.10"
date <- as.Date(sdate4) # ==> This will generate the same error"""Error in charToDate(x): character string is not in a standard unambiguous format""".
date <- as.Date(sdate4, format = "%Y.%m.%d") # ==> Error Free Date Conversion.
You want rows where that condition is true so you need a comma:
data[data$Ozone > 14, ]
For those wanting to use a Class.
Create a Class with all the parameters you want
Create a list with the class as parameter
class MyClass_x000D_
{_x000D_
public string S1;_x000D_
public string S2;_x000D_
}_x000D_
_x000D_
List<MyClass> MyList= new List<MyClass>();
_x000D_
I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:
CAST(YourValueHere as smalldatetime);
For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.
The RemoveInvalidXmlChars method provided by Irishman does not support surrogate characters. To test it, use the following example:
static void Main()
{
const string content = "\v\U00010330";
string newContent = RemoveInvalidXmlChars(content);
Console.WriteLine(newContent);
}
This returns an empty string but it shouldn't! It should return "\U00010330" because the character U+10330 is a valid XML character.
To support surrogate characters, I suggest using the following method:
public static string RemoveInvalidXmlChars(string text)
{
if (string.IsNullOrEmpty(text))
return text;
int length = text.Length;
StringBuilder stringBuilder = new StringBuilder(length);
for (int i = 0; i < length; ++i)
{
if (XmlConvert.IsXmlChar(text[i]))
{
stringBuilder.Append(text[i]);
}
else if (i + 1 < length && XmlConvert.IsXmlSurrogatePair(text[i + 1], text[i]))
{
stringBuilder.Append(text[i]);
stringBuilder.Append(text[i + 1]);
++i;
}
}
return stringBuilder.ToString();
}
In addition to cozeJ4's answer, here's updated version of that gist
Original one lacked imports and contained some errors. This one is ready to use.
In order to load local images to your React.js application, you need to add require
parameter in media sections like or Image tags, as below:
image={require('./../uploads/temp.jpg')}
In the BcryptHasher.php you can find the hash code:
public function make($value, array $options = array())
{
$cost = isset($options['rounds']) ? $options['rounds'] : $this->rounds;
$hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));
$hash = password_hash($value, PASSWORD_BCRYPT, array('cost' => $cost));
echo $value.' '.PASSWORD_BCRYPT.' '.$cost.' ';
echo $hash;die();
if ($hash === false)
{
throw new RuntimeException("Bcrypt hashing not supported.");
}
return $hash;
}
yourarray.shape
or np.shape()
or np.ma.shape()
returns the shape of your ndarray as a tuple; And you can get the (number of) dimensions of your array using yourarray.ndim
or np.ndim()
. (i.e. it gives the n
of the ndarray
since all arrays in NumPy are just n-dimensional arrays (shortly called as ndarray
s))
For a 1D array, the shape would be (n,)
where n
is the number of elements in your array.
For a 2D array, the shape would be (n,m)
where n
is the number of rows and m
is the number of columns in your array.
Please note that in 1D case, the shape would simply be (n, )
instead of what you said as either (1, n)
or (n, 1)
for row and column vectors respectively.
This is to follow the convention that:
For 1D array, return a shape tuple with only 1 element (i.e. (n,)
)
For 2D array, return a shape tuple with only 2 elements (i.e. (n,m)
)
For 3D array, return a shape tuple with only 3 elements (i.e. (n,m,k)
)
For 4D array, return a shape tuple with only 4 elements (i.e. (n,m,k,j)
)
and so on.
Also, please see the example below to see how np.shape()
or np.ma.shape()
behaves with 1D arrays and scalars:
# sample array
In [10]: u = np.arange(10)
# get its shape
In [11]: np.shape(u) # u.shape
Out[11]: (10,)
# get array dimension using `np.ndim`
In [12]: np.ndim(u)
Out[12]: 1
In [13]: np.shape(np.mean(u))
Out[13]: () # empty tuple (to indicate that a scalar is a 0D array).
# check using `numpy.ndim`
In [14]: np.ndim(np.mean(u))
Out[14]: 0
P.S.: So, the shape tuple is consistent with our understanding of dimensions of space, at least mathematically.
Fix for new Android 6.0 Marshmallow Fixed my issue when I updated to API 23 (Android 6.0 Marshmallow) by updating the build tools version to 23.0.0 as follows:
android {
buildToolsVersion '23.0.0'
...
And went to File > Project Structure , chose Properties tab then updated the Compile Sdk version to "API 23: Android 5.X (MNC)" and the Build tools version to "23.0.0"
For the record, rjson and RJSONIO do change the file type, but they don't really parse per se. For instance, I receive ugly MongoDB data in JSON format, convert it with rjson or RJSONIO, then use unlist and tons of manual correction to actually parse it into a usable matrix.
May I suggest Node ORM?
https://github.com/dresende/node-orm2
There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.
MongoDB is available since version 2.1.x (released in July 2013)
UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize
As noted by StingyJack and mcbala, and in reference to comments made by Mike L, my experience is that on a Windows 2000 machine, when uninstalling / reinstalling .Net services, "installutil /u" does require a reboot, even when the service was previously stopped. "sc /delete", on the other hand, does not require a reboot - it deletes the service right away (as long as it is stopped).
I have often wondered, actually, whether there is a good reason "installutil /u" requires a reboot... Is "sc /delete" actually doing something wrong / leaving something hanging?
The exit
function is declared in the stdlib header, so you need to have
#include <stdlib.h>
at the top of your program to be able to use exit
.
Note also that exit
takes an integer argument, so you can't call it like exit()
, you have to call as exit(0)
or exit(42)
. 0 usually means your program completed successfully, and nonzero values are used as error codes.
There are also predefined macros EXIT_SUCCESS
and EXIT_FAILURE
, e.g. exit(EXIT_SUCCESS);
You have to create an item of type ListBoxItem and add that to the Items collection:
list.Items.add( new ListBoxItem("clan", "sifOsoba"));
You do it like this:
df = read.table("file.txt", nrows=1, header=TRUE, sep="\t", stringsAsFactors=FALSE)
colClasses = as.list(apply(df, 2, class))
needCols = c("Year", "Jan", "Feb", "Mar", "Apr", "May", "Jun")
colClasses[!names(colClasses) %in% needCols] = list(NULL)
df = read.table("file.txt", header=TRUE, colClasses=colClasses, sep="\t", stringsAsFactors=FALSE)
You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".
http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector
.class {
margin:20px;
&:hover {
color:yellow;
}
}
Like @CoolBeans mentioned, take a look at jUnit. Here is a short tutorial to get you started as well with jUnit 4.x
Finally, if you really want to learn more about testing and test-driven development (TDD) I recommend you take a look at the following book by Kent Beck: Test-Driven Development By Example.
From my recent experience, JsonReader#setLenient
basically makes the parser very tolerant, even to allow malformed JSON data.
But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim
the data would avoid the error:
String trimmed = result1.trim();
Then gson.fromJson(trimmed, T)
might work. Surely this only covers a special case, so YMMV.
Try Ctrl + K + D (don't lift the Ctrl key in between).
did you try something like
for o : AnyObject in self.subviews {
if let v = o as? NSView {
v.removeFromSuperview()
}
}
I just recently, after seven long years with Maven, learned about toolchains.xml. Maven has it even documented and supports it from 2.0.9 - toolchains documentation
So I added a toolchain.xml file to my ~/.m2/ folder with following content:
<toolchains xmlns="http://maven.apache.org/TOOLCHAINS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/TOOLCHAINS/1.1.0 http://maven.apache.org/xsd/toolchains-1.1.0.xsd">
<!-- JDK toolchains -->
<toolchain>
<type>jdk</type>
<provides>
<version>1.8</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/opt/java8</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>1.7</version>
<vendor>sun</vendor>
</provides>
<configuration>
<jdkHome>/opt/java7</jdkHome>
</configuration>
</toolchain>
</toolchains>
It allows you to define what different JDKs Maven can use to build the project irrespective of the JDK Maven runs with. Sort of like when you define JDK on project level in IDE.
I think you can just do
std::string s( MyVector.begin(), MyVector.end() );
where MyVector is your std::vector.
JsonNode
is immutable and is intended for parse operation. However, it can be cast into ObjectNode
(and ArrayNode
) that allow mutations:
((ObjectNode)jsonNode).put("value", "NO");
For an array, you can use:
((ObjectNode)jsonNode).putArray("arrayName").add(object.ge??tValue());
Please see the following information from user Pekka ?
According to the manual, destructors are executed even if the script gets terminated using die()
or exit()
:
The destructor will be called even if script execution is stopped using exit()
. Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
According to this PHP: destructor vs register_shutdown_function, the destructor does not get executed when PHP's execution time limit is reached (Confirmed on Apache 2, PHP 5.2 on Windows 7).
The destructor also does not get executed when the script terminates because the memory limit was reached. (Just tested)
The destructor does get executed on fatal errors (Just tested) Update: The OP can't confirm this - there seem to be fatal errors where things are different
It does not get executed on parse errors (because the whole script won't be interpreted)
The destructor will certainly not be executed if the server process crashes or some other exception out of PHP's control occurs.
Referenced in this question Are there any instances when the destructor in PHP is NOT called?
Not only is the boolean datatype missing in Oracle's SQL (not PL/SQL), but they also have no clear recommendation about what to use instead. See this thread on asktom. From recommending CHAR(1) 'Y'/'N'
they switch to NUMBER(1) 0/1
when someone points out that 'Y'/'N'
depends on the English language, while e.g. German programmers might use 'J'/'N'
instead.
The worst thing is that they defend this stupid decision just like they defend the ''=NULL
stupidity.
One thing that might not always be obvious to some is that a cross join with an empty table (or result set) results in empty table (M x N; hence M x 0 = 0)
A full outer join will always have rows unless both M and N are 0.
I tried all of above. What helps me:
this C:\MinGW\bin
to environment variables.mingw-get
into command line.mingw-get install mingw32-make
.C:\MinGW\bin
to folder where your Makefile is.
Done! Now You might be able to use make-commands in this folder.Here's an accessible solution
label {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
label input {_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
label:focus-within {_x000D_
outline: 1px solid orange;_x000D_
}
_x000D_
<div class="radio-toolbar">_x000D_
<label><input type="radio" value="all" checked>All</label>_x000D_
<label><input type="radio" value="false">Open</label>_x000D_
<label><input type="radio" value="true">Archived</label>_x000D_
</div>
_x000D_
For python 3 it would be like this
n,m,p=map(int,input().split())
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
here is my code to find the next empty row for example in first row 'A'. To use it for any other row just change cells(i,2 or 3 or 4 so on)
Sheets("Sheeet1").Select
for i=1 to 5000
if cells(i,1)="" then nextEmpty=i goto 20
next i
20 'continue your code here
enter code here
I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
I found very good link for JSON: http://code.google.com/p/json-simple/wiki/EncodingExamples#Example_1-1_-_Encode_a_JSON_object
Here's code to add multiple JSONObjects to JSONArray.
JSONArray Obj = new JSONArray();
try {
for(int i = 0; i < 3; i++) {
// 1st object
JSONObject list1 = new JSONObject();
list1.put("val1",i+1);
list1.put("val2",i+2);
list1.put("val3",i+3);
obj.put(list1);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Toast.makeText(MainActivity.this, ""+obj, Toast.LENGTH_LONG).show();
I would have to answer that private fields in Java are inherited. Allow me to demonstrate:
public class Foo {
private int x; // This is the private field.
public Foo() {
x = 0; // Sets int x to 0.
}
//The following methods are declared "final" so that they can't be overridden.
public final void update() { x++; } // Increments x by 1.
public final int getX() { return x; } // Returns the x value.
}
public class Bar extends Foo {
public Bar() {
super(); // Because this extends a class with a constructor, it is required to run before anything else.
update(); //Runs the inherited update() method twice
update();
System.out.println(getX()); // Prints the inherited "x" int.
}
}
If you run in a program Bar bar = new Bar();
, then you will always see the number "2" in the output box. Because the integer "x" is encapsulated with the methods update()
and getX()
, then it can be proven that the integer is inherited.
The confusion is that because you can't directly access the integer "x", then people argue that it isn't inherited. However, every non-static thing in a class, be it field or method, is inherited.
Data contract: It specifies that your entity class is ready for Serialization process.
Data members: It specifies that the particular field is part of the data contract and it can be serialized.
In PHP 7.0 it's now possible to use Null coalescing operator:
echo "My index value is: " . ($my_array["my_index"] ?? '');
Equals to:
echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');
In Linux, run file on the Eclipse executable, like this:
$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped
Another reason this could be happening is if you are using an iframe that has the sandbox attribute and allow-same-origin
isn't set e.g.:
// page.html
<iframe id="f" src="http://localhost:8000/iframe.html" sandbox="allow-scripts"></iframe>
<script type="text/javascript">
var f = document.getElementById("f").contentWindow;
// will throw exception
f.postMessage("hello world!", 'http://localhost:8000');
</script>
// iframe.html
<script type="text/javascript">
window.addEventListener("message", function(event) {
console.log(event);
}, false);
</script>
I haven't found a solution other than:
f.postMessage("hello world!", '*');
Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
This would change your serif latex font. You can also specify the sans-serif Helvetica like so
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
Other options are cursive
and monospace
with their respective font names.
Your label would then be
fig.gca().set_xlabel(r'wavelength $5000 \AA$')
If the font doesn't supply an Angstrom symbol you can try using \mathring{A}
* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080' ^^^^^
The https://
is wrong, it should be http://
. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.
Possible and easiest one-line solution is to use:
file_get_contents("YOUR_REQUESTED_FILE");
Or equivavelt for example CURL.
Control-C works, although depending on what the process is doing it might not take right away.
If you're on a unix based system, one thing I do is control-z to go back to the command line prompt and then issue a 'kill' to the process ID.
I needed column names as a flat array, while the other answers returned associative arrays, so I used:
$con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);
$table = 'people';
/**
* Get the column names for a mysql table
**/
function get_column_names($con, $table) {
$sql = 'DESCRIBE '.$table;
$result = mysqli_query($con, $sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row['Field'];
}
return $rows;
}
$col_names = function get_column_names($con, $table);
$col_names now equals:
(
[0] => name
[1] => parent
[2] => number
[3] => chart_id
[4] => type
[5] => id
)
You may directly right-click on the table name - that also shows the "Import Data.." option.Then you can follow few simple steps & succeed.
Do anyone know how to import a new table with data from excel?
The problem is the linker is looking for libmagic.so
but you only have libmagic.so.1
A quick hack is to symlink libmagic.so.1
to libmagic.so
Many in the community would prefer no limit with warnings about performance, see this comment for a well reasoned argument: https://jira.mongodb.org/browse/SERVER-431?focusedCommentId=22283&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-22283
My take, the lead developers are stubborn about this issue because they decided it was an important "feature" early on. They're not going to change it anytime soon because their feelings are hurt that anyone questioned it. Another example of personality and politics detracting from a product in open source communities but this is not really a crippling issue.
I think this will benefit you Try this I'm using to change the language in my application
String[] districts;
Spinner sp;
......
sp = (Spinner) findViewById(R.id.sp);
districts = getResources().getStringArray(R.array.lang_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,districts);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You select "+districts[index]+" id "+position, Toast.LENGTH_LONG).show();
switch(position){
case 0:
setLocal("fr");
//recreate();
break;
case 1:
setLocal("ar");
//recreate();
break;
case 2:
setLocal("en");
//recreate();
break;
default: //For all other cases, do this
setLocal("en");
//recreate();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
and this is my String Array
<string-array name="lang_array">
<item>french</item>
<item>arabic</item>
<item>english</item>
</string-array>
use below
UIImageView *imageView = ((UIImageView *)(barButtonItem.customView.subviews.lastObject));
file_name = imageView.accessibilityLabel;
Please check if you have the following entries in the element of your pom.xml especially the jdk.version because switching to an installed jre did not fix me the similar error.
<properties>
<jdk.version>1.7</jdk.version>
<spring.version>4.1.1.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<junit.version>4.11</junit.version>
</properties>
impdp
exports the DDL of a dmp
backup to a file if you use the SQLFILE
parameter. For example, put this into a text file
impdp '/ as sysdba' dumpfile=<your .dmp file> logfile=import_log.txt sqlfile=ddl_dump.txt
Then check ddl_dump.txt
for the tablespaces, users, and schemas in the backup.
According to the documentation, this does not actually modify the database:
The SQL is not actually executed, and the target system remains unchanged.
So, answering my own question here. We ultimately determined that we were seeing 502 and 503 errors in the load balancer due to Tomcat threads timing out. In the short term we increased the timeout. In the longer term, we fixed the app problems that were causing the timeouts in the first place. Why Tomcat timeouts were being perceived as 502 and 503 errors at the load balancer is still a bit of a mystery.
i also face same problem.i found solution for that.
bcrypt required C++, python and node-pre-gyp.
sudo apt-get install g++
sudo apt-get install -y build-essential python
npm install node-pre-gyp
for more details check : https://github.com/kelektiv/node.bcrypt.js/wiki/Installation-Instructions#ubuntu-and-derivatives---elementary-linux-mint-etc
If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.
In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..
I disabled Chrome extension "Coupons at Checkout" and this problem was solved.
If a
is your array:
In [11]: a[:,:2]
Out[11]:
array([[-0.57098887, -0.4274751 ],
[-0.22279713, -0.51723555],
[ 0.67492385, -0.69294472],
[ 0.41086611, 0.26374238]])
I find this to be the friendliest and most concise way to post an read JSON data:
var url = @"http://www.myapi.com/";
var request = new Request { Greeting = "Hello world!" };
var json = JsonSerializer.Serialize<Request>(request);
using (WebClient client = new WebClient())
{
var jsonResponse = client.UploadString(url, json);
var response = JsonSerializer.Deserialize<Response>(jsonResponse);
}
I'm using Microsoft's System.Text.Json
for serializing and deserializing JSON. See NuGet.
I did it like this so it was cross-compatible with old browsers.
// For really old browser's or incompatible ones
function getOffsetSum(elem) {
var top = 0,
left = 0,
bottom = 0,
right = 0
var width = elem.offsetWidth;
var height = elem.offsetHeight;
while (elem) {
top += elem.offsetTop;
left += elem.offsetLeft;
elem = elem.offsetParent;
}
right = left + width;
bottom = top + height;
return {
top: top,
left: left,
bottom: bottom,
right: right,
}
}
function getOffsetRect(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop;
var clientLeft = docElem.clientLeft;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
var bottom = top + (box.bottom - box.top);
var right = left + (box.right - box.left);
return {
top: Math.round(top),
left: Math.round(left),
bottom: Math.round(bottom),
right: Math.round(right),
}
}
function getOffset(elem) {
if (elem) {
if (elem.getBoundingClientRect) {
return getOffsetRect(elem);
} else { // old browser
return getOffsetSum(elem);
}
} else
return null;
}
More about coordinates in JavaScript here: http://javascript.info/tutorial/coordinates
I wrote a quick and dirty app the other day for doing this using Google API. Most certainly scope for improvement...
Find it here with a live demo and code.
I did not post the code here simply because I keep on refining it and hopefully when I have time, convert it into a proper class.
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
Go to file \phpMyAdmin\config.inc.php at the very bottom, change the hosting details such as host, username, password etc.
SQL Authentication
SQL Authentication is the typical authentication used for various database systems, composed of a username and a password. Obviously, an instance of SQL Server can have multiple such user accounts (using SQL authentication) with different usernames and passwords. In shared servers where different users should have access to different databases, SQL authentication should be used. Also, when a client (remote computer) connects to an instance of SQL Server on other computer than the one on which the client is running, SQL Server authentication is needed. Even if you don't define any SQL Server user accounts, at the time of installation a root account - sa - is added with the password you provided. Just like any SQL Server account, this can be used to log-in localy or remotely, however if an application is the one that does the log in, and it should have access to only one database, it's strongly recommended that you don't use the sa account, but create a new one with limited access. Overall, SQL authentication is the main authentication method to be used while the one we review below - Windows Authentication - is more of a convenience.
Windows Authentication
When you are accessing SQL Server from the same computer it is installed on, you shouldn't be prompted to type in an username and password. And you are not, if you're using Windows Authentication. With Windows Authentication, the SQL Server service already knows that someone is logged in into the operating system with the correct credentials, and it uses these credentials to allow the user into its databases. Of course, this works as long as the client resides on the same computer as the SQL Server, or as long as the connecting client matches the Windows credentials of the server. Windows Authentication is often used as a more convenient way to log-in into a SQL Server instance without typing a username and a password, however when more users are envolved, or remote connections are being established with the SQL Server, SQL authentication should be used.
A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:
DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");
A (partial) practical work-around is to put things into a throw-away function.
Pasting
x = 1
x += 1
print(x)
results in
>>> x = 1
x += 1
print(x)
File "<stdin>", line 1
x += 1
print(x)
^
SyntaxError: multiple statements found while compiling a single statement
>>>
However, pasting
def abc():
x = 1
x += 1
print(x)
works:
>>> def abc():
x = 1
x += 1
print(x)
>>> abc()
2
>>>
Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython
/ jupyter qtconsole
is probably the next simplest option.
The accepted answer is great, but if you need to interact programmatically with PostgreSQL version maybe it's better to do:
SELECT current_setting('server_version_num'); -- Returns 90603 (9.6.3)
-- Or using SHOW command:
SHOW server_version_num; -- Returns 90603 too
It will return server version as an integer. This is how server version is tested in PostgreSQL source, e.g.:
/*
* This is a C code from pg_dump source.
* It will do something if PostgreSQL remote version (server) is lower than 9.1.0
*/
if (fout->remoteVersion < 90100)
/*
* Do something...
*/
Similar issues on macOS Catalina and the issue turned out to be the version of Java that I was running. By default, when Java is installed now, it's version 13, which does not work with the current version of avd.
Additionally, I had trouble installing Java 8, so I used the one that's available in Homebrew:
brew cask install homebrew/cask-versions/adoptopenjdk8
Then, in my ~/.profile
I set the Java version to 1.8:
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)
Now it's possible to test if the avdmanager can run and detect the virtual devices (previously, this resulted in an error saying the XML cannot be parsed):
avdmanager list avds
I tried gitosis that is fully command line. And I chose this one.
Being a Java guy, I also looked with interest to Gitblit.
{{ form_widget(form.content, { 'attr': {'class': 'tinyMCE', 'data-theme': 'advanced'} }) }}
Faced more issues while making this work. Here are the details:
apache-log4j-extras-1.1.jar
in the classpath, didn't notice this at first.RollingFileAppender
should be org.apache.log4j.rolling.RollingFileAppender
instead of org.apache.log4j.RollingFileAppender
. This can give the error: log4j:ERROR No output stream or file set for the appender named [file].
log4j-1.2.14.jar
to log4j-1.2.16.jar
.Below is the appender configuration which worked for me:
<appender name="file" class="org.apache.log4j.rolling.RollingFileAppender">
<param name="threshold" value="debug" />
<rollingPolicy name="file"
class="org.apache.log4j.rolling.TimeBasedRollingPolicy">
<param name="FileNamePattern" value="logs/MyLog-%d{yyyy-MM-dd-HH-mm}.log.gz" />
<!-- The below param will keep the live update file in a different location-->
<!-- param name="ActiveFileName" value="current/MyLog.log" /-->
</rollingPolicy>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" />
</layout>
</appender>
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
https://github.com/reoxey/benchmark
benchmark
speed comparison of MySQL & MongoDB in GOLANG1.6 & PHP5
system used for benchmark: DELL cpu i5 4th gen 1.70Ghz * 4 ram 4GB GPU ram 2GB
Speed comparison of RDBMS vs NoSQL for INSERT, SELECT, UPDATE, DELETE executing different number of rows 10,100,1000,10000,100000,1000000
Language used to execute is: PHP5 & Google fastest language GO 1.6
________________________________________________
GOLANG with MySQL (engine = MyISAM)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 1.195444ms
100 6.075053ms
1000 47.439699ms
10000 483.999809ms
100000 4.707089053s
1000000 49.067407174s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 872.709µs
SELECT & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 20.717354746s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 2.309209968s
100000 257.411502ms
10000 26.73954ms
1000 3.483926ms
100 915.17µs
10 650.166µs
DELETE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 6.065949ms
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
GOLANG with MongoDB
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 2.067094ms
100 8.841597ms
1000 106.491732ms
10000 998.225023ms
100000 8.98172825s
1000000 1m 29.63203158s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 5.251337439s
FIND & DISPLAY (with index declared)
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 21.540603252s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1 1.330954ms
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
PHP5 with MySQL (engine = MyISAM)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 0.0040680000000001s
100 0.011595s
1000 0.049718s
10000 0.457164s
100000 4s
1000000 42s
SELECT
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 <1s
SELECT & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 20s
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
________________________________________________
PHP5 with MongoDB
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
INSERT
------------------------------------------------
num of rows time taken
------------------------------------------------
10 0.065744s
100 0.190966s
1000 0.2163s
10000 1s
100000 8s
1000000 78s
FIND
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 <1s
FIND & DISPLAY
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 7s
UPDATE
------------------------------------------------
num of rows time taken
------------------------------------------------
1000000 9s
On your branch - say master, pull and allow unrelated histories
git pull origin master --allow-unrelated-histories
Worked for me.
In the root open the .editorconfig file and change:
end_of_line = lf
to
end_of_line = auto
This should fix it for new files.
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding.
I'd like to point to this excellent answer by zneak on why double shouldn't be used.
You could subscribe for the change and keyup events:
$(function() {
$(':input').change(myFunction).keyup(myFunction);
});
where myFunction
is the function you would like executed:
function myFunction() {
alert( 'something happened!' );
}
One more way:
scala> val xs = Array("first", "second", "third")
xs: Array[java.lang.String] = Array(first, second, third)
scala> for (i <- xs.indices)
| println(i + ": " + xs(i))
0: first
1: second
2: third
You should use empty()
@if (!empty($status->replies))
<div class="media-body reply-body">
@foreach ($status->replies as $reply)
<p>{{ $reply->body }}</p>
@endforeach
</div>
@endif
You can use count, but if the array is larger it takes longer, if you only need to know if its empty, empty is the better one to use.
For database :
USE db_name; SELECT @@character_set_database;
This is a simplified example with IEnumerable.
I was using two models on the view: a form with search criteria (SearchParams model), and a grid for results, and I struggled with how to add the IEnumerable model and the other model on the same view. Here is what I came up with, hope this helps someone:
@using DelegatePortal.ViewModels;
@model SearchViewModel
@using (Html.BeginForm("Search", "Delegate", FormMethod.Post))
{
Employee First Name
@Html.EditorFor(model => model.SearchParams.FirstName,
new { htmlAttributes = new { @class = "form-control form-control-sm " } })
<input type="submit" id="getResults" value="SEARCH" class="btn btn-primary btn-lg btn-block" />
}
<br />
@(Html
.Grid(Model.Delegates)
.Build(columns =>
{
columns.Add(model => model.Id).Titled("Id").Css("collapse");
columns.Add(model => model.LastName).Titled("Last Name");
columns.Add(model => model.FirstName).Titled("First Name");
})
... )
SearchViewModel.cs:
namespace DelegatePortal.ViewModels
{
public class SearchViewModel
{
public IEnumerable<DelegatePortal.Models.DelegateView> Delegates { get; set; }
public SearchParamsViewModel SearchParams { get; set; }
....
DelegateController.cs:
// GET: /Delegate/Search
public ActionResult Search(String firstName)
{
SearchViewModel model = new SearchViewModel();
model.Delegates = db.Set<DelegateView>();
return View(model);
}
// POST: /Delegate/Search
[HttpPost]
public ActionResult Search(SearchParamsViewModel searchParams)
{
String firstName = searchParams.FirstName;
SearchViewModel model = new SearchViewModel();
if (firstName != null)
model.Delegates = db.Set<DelegateView>().Where(x => x.FirstName == firstName);
return View(model);
}
SearchParamsViewModel.cs:
namespace DelegatePortal.ViewModels
{
public class SearchParamsViewModel
{
public string FirstName { get; set; }
}
}
+
means a space only in application/x-www-form-urlencoded
content, such as the query part of a URL:
http://www.example.com/path/foo+bar/path?query+name=query+value
In this URL, the parameter name is query name
with a space and the value is query value
with a space, but the folder name in the path is literally foo+bar
, not foo bar
.
%20
is a valid way to encode a space in either of these contexts. So if you need to URL-encode a string for inclusion in part of a URL, it is always safe to replace spaces with %20
and pluses with %2B
. This is what eg. encodeURIComponent()
does in JavaScript. Unfortunately it's not what urlencode does in PHP (rawurlencode is safer).
See Also HTML 4.01 Specification application/x-www-form-urlencoded
SELECT
AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit,
BillLimit, Mode, PNotes, gtab82.memno
FROM
VCustomer AS v1
INNER JOIN
gtab82 ON gtab82.memacid = v1.AcId
WHERE (AcGrCode = '204' OR CreDebt = 'True')
AND Masked = 'false'
ORDER BY AcName
You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer
but only use it in the ON
clause for uncertain reasons. You may want to review that aspect of your code.
You can clone it to get the entire contents, like this:
var html = $("<div />").append($("#div1").clone()).html();
Or make it a plugin, most tend to call this "outerHTML", like this:
jQuery.fn.outerHTML = function() {
return jQuery('<div />').append(this.eq(0).clone()).html();
};
Then you can just call:
var html = $("#div1").outerHTML();
Active is when the user activating that point (Like mouse clicking, if we use tab from field-to-field there is no sign from active style. Maybe clicking need more time, just try hold click on that point), focus is happened after the point is activated. Try this :
<style type="text/css">
input { font-weight: normal; color: black; }
input:focus { color: green; outline: 1px solid green; }
input:active { color: red; outline: 1px solid red; }
</style>
<input type="text"/>
<input type="text"/>
using eval:
var part1name = eval("someObject.part1.name");
wrap to return undefined on error
function path(obj, path) {
try {
return eval("obj." + path);
} catch(e) {
return undefined;
}
}
http://jsfiddle.net/shanimal/b3xTw/
Please use common sense and caution when wielding the power of eval. It's a bit like a light saber, if you turn it on there's a 90% chance you'll sever a limb. Its not for everybody.
To find commits from the branching point, you could use this.
git log --ancestry-path master..topicbranch
You are right this is inconsistent. What is happening is that CheckBox doesn't HAVE an server-side OnClick event, so your markup gets rendered to the browser. http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox_events.aspx
Whereas Button does have a OnClick - so ASP.NET expects a reference to an event in your OnClick markup.
download the mysql-5.0.23-win32.zip (this is the smallest possible one) from archived versions in mysql.com website
cut and paste the installation in c drive as mysql folder
then install then follow instructions as per this page: https://cyleft.wordpress.com/2008/07/20/fixing-mysql-service-could-not-start-1067-errors/
Dynamic analysis methods
Here I describe a few dynamic analysis methods.
Dynamic methods actually run the program to determine the call graph.
The opposite of dynamic methods are static methods, which try to determine it from the source alone without running the program.
Advantages of dynamic methods:
Disadvantages of dynamic methods:
KcacheGrind
https://kcachegrind.github.io/html/Home.html
Test program:
int f2(int i) { return i + 2; }
int f1(int i) { return f2(2) + i + 1; }
int f0(int i) { return f1(1) + f2(2); }
int pointed(int i) { return i; }
int not_called(int i) { return 0; }
int main(int argc, char **argv) {
int (*f)(int);
f0(1);
f1(1);
f = pointed;
if (argc == 1)
f(1);
if (argc == 2)
not_called(1);
return 0;
}
Usage:
sudo apt-get install -y kcachegrind valgrind
# Compile the program as usual, no special flags.
gcc -ggdb3 -O0 -o main -std=c99 main.c
# Generate a callgrind.out.<PID> file.
valgrind --tool=callgrind ./main
# Open a GUI tool to visualize callgrind data.
kcachegrind callgrind.out.1234
You are now left inside an awesome GUI program that contains a lot of interesting performance data.
On the bottom right, select the "Call graph" tab. This shows an interactive call graph that correlates to performance metrics in other windows as you click the functions.
To export the graph, right click it and select "Export Graph". The exported PNG looks like this:
From that we can see that:
_start
, which is the actual ELF entry point, and contains glibc initialization boilerplatef0
, f1
and f2
are called as expected from one anotherpointed
is also shown, even though we called it with a function pointer. It might not have been called if we had passed a command line argument.not_called
is not shown because it didn't get called in the run, because we didn't pass an extra command line argument.The cool thing about valgrind
is that it does not require any special compilation options.
Therefore, you could use it even if you don't have the source code, only the executable.
valgrind
manages to do that by running your code through a lightweight "virtual machine". This also makes execution extremely slow compared to native execution.
As can be seen on the graph, timing information about each function call is also obtained, and this can be used to profile the program, which is likely the original use case of this setup, not just to see call graphs: How can I profile C++ code running on Linux?
Tested on Ubuntu 18.04.
gcc -finstrument-functions
+ etrace
https://github.com/elcritch/etrace
-finstrument-functions
adds callbacks, etrace parses the ELF file and implements all callbacks.
I couldn't get it working however unfortunately: Why doesn't `-finstrument-functions` work for me?
Claimed output is of format:
\-- main
| \-- Crumble_make_apple_crumble
| | \-- Crumble_buy_stuff
| | | \-- Crumble_buy
| | | \-- Crumble_buy
| | | \-- Crumble_buy
| | | \-- Crumble_buy
| | | \-- Crumble_buy
| | \-- Crumble_prepare_apples
| | | \-- Crumble_skin_and_dice
| | \-- Crumble_mix
| | \-- Crumble_finalize
| | | \-- Crumble_put
| | | \-- Crumble_put
| | \-- Crumble_cook
| | | \-- Crumble_put
| | | \-- Crumble_bake
Likely the most efficient method besides specific hardware tracing support, but has the downside that you have to recompile the code.
The position: fixed;
solution has a drawback - the page jumps to the top when this style is applied. Angular's Material Dialog has a nice solution, where they fake the scroll position by applying positioning to the html
element.
Below is my revised algorithm for vertical scrolling only. Left scroll blocking is done in the exact same manner.
// This class applies the following styles:
// position: fixed;
// overflow-y: scroll;
// width: 100%;
const NO_SCROLL_CLASS = "bp-no-scroll";
const coerceCssPixelValue = value => {
if (value == null) {
return "";
}
return typeof value === "string" ? value : `${value}px`;
};
export const blockScroll = () => {
const html = document.documentElement;
const documentRect = html.getBoundingClientRect();
const { body } = document;
// Cache the current scroll position to be restored later.
const cachedScrollPosition =
-documentRect.top || body.scrollTop || window.scrollY || document.scrollTop || 0;
// Cache the current inline `top` value in case the user has set it.
const cachedHTMLTop = html.style.top || "";
// Using `html` instead of `body`, because `body` may have a user agent margin,
// whereas `html` is guaranteed not to have one.
html.style.top = coerceCssPixelValue(-cachedScrollPosition);
// Set the magic class.
html.classList.add(NO_SCROLL_CLASS);
// Return a function to remove the scroll block.
return () => {
const htmlStyle = html.style;
const bodyStyle = body.style;
// We will need to seamlessly restore the original scroll position using
// `window.scroll`. To do that we will change the scroll behavior to `auto`.
// Here we cache the current scroll behavior to restore it later.
const previousHtmlScrollBehavior = htmlStyle.scrollBehavior || "";
const previousBodyScrollBehavior = bodyStyle.scrollBehavior || "";
// Restore the original inline `top` value.
htmlStyle.top = cachedHTMLTop;
// Remove the magic class.
html.classList.remove(NO_SCROLL_CLASS);
// Disable user-defined smooth scrolling temporarily while we restore the scroll position.
htmlStyle.scrollBehavior = bodyStyle.scrollBehavior = "auto";
// Restore the original scroll position.
window.scroll({
top: cachedScrollPosition.top
});
// Restore the original scroll behavior.
htmlStyle.scrollBehavior = previousHtmlScrollBehavior;
bodyStyle.scrollBehavior = previousBodyScrollBehavior;
};
};
The logic is very simple and can be simplified even more if you don't care about certain edge cases. For example, this is what I use:
export const blockScroll = () => {
const html = document.documentElement;
const documentRect = html.getBoundingClientRect();
const { body } = document;
const screenHeight = window.innerHeight;
// Only do the magic if document is scrollable
if (documentRect.height > screenHeight) {
const cachedScrollPosition =
-documentRect.top || body.scrollTop || window.scrollY || document.scrollTop || 0;
html.style.top = coerceCssPixelValue(-cachedScrollPosition);
html.classList.add(NO_SCROLL_CLASS);
return () => {
html.classList.remove(NO_SCROLL_CLASS);
window.scroll({
top: cachedScrollPosition,
behavior: "auto"
});
};
}
};
Inspired by Steve, and as the updates for Java 11. Here's how we did the BigDecimal reformatting to avoid scientific notation.
public class PriceSerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
// Using writNumber and removing toString make sure the output is number but not String.
jgen.writeNumber(value.setScale(2, RoundingMode.HALF_UP));
}
}
Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit
<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
{{$index}} - {{day.iso}} - {{day.name}}
Temperature: {{f.temperature}}<br>
Humidity: {{f.humidity}}<br>
...
</div>
Example: http://jsfiddle.net/coma/UV4qF/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$rt = curl_exec($ch);
$info = curl_getinfo($ch);
echo $info["http_code"];
If anyone getting this in unit/instrumentation testing, make sure you call getFilesDir()
on the app context, not the test context. i.e. use:
Context appContext = getInstrumentation().getTargetContext().getApplicationContext();
not
Context appContext = InstrumentationRegistry.getContext;
I've tried both these and still get failure due to conflicts. At the end of my patience, I cloned master in another location, copied everything into the other branch and committed it. which let me continue. The "-X theirs" option should have done this for me, but it did not.
git merge -s recursive -X theirs master
error: 'merge' is not possible because you have unmerged files. hint: Fix them up in the work tree, hint: and then use 'git add/rm ' as hint: appropriate to mark resolution and make a commit, hint: or use 'git commit -a'. fatal: Exiting because of an unresolved conflict.
One way of doing it is to use the ClientScriptManager
:
Page.ClientScript.RegisterStartupScript(
GetType(),
"MyKey",
"Myfunction();",
true);
Easy enough to use underscore:
_.escape(string)
Underscore is a utility library that provides a lot of features that native js doesn't provide. There's also lodash which is the same API as underscore but was rewritten to be more performant.
//Get Connection from web.config file
public static OdbcConnection getConnection()
{
OdbcConnection con = new OdbcConnection();
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["con"].ConnectionString;
return con;
}
For iOS 10.x and Swift 3.x [below versions are also supported] just add the following lines in 'info.plist'
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
I had similar problem, got this resolved by the following CSS:
body {
margin: 0 !important;
padding: 0 !important;
}
You can use jstack utility if you want to check the current call stack of your process.
Usage:
jstack [-l] <pid>
(to connect to running process)
jstack -F [-m] [-l] <pid>
(to connect to a hung process)
jstack [-m] [-l] <executable> <core>
(to connect to a core file)
jstack [-m] [-l] [server_id@]<remote server IP or hostname>
(to connect to a remote debug server)
Options:
-F to force a thread dump. Use when jstack <pid> does not respond (process is hung)
-m to print both java and native frames (mixed mode)
-l long listing. Prints additional information about locks
-h or -help to print this help message
You should try delimit it can open up to 2 billion rows and 2 million columns very quickly has a free 15 day trial too. Does the job for me!
I would consider using roboguice's logging facility instead of the built-in android.util.Log
Their facility automatically disables debug and verbose logs for release builds. Plus, you get some nifty features for free (e.g. customizable logging behavior, additional data for every log and more)
Using proguard could be quite a hassle and I wouldn't go through the trouble of configuring and making it work with your application unless you have a good reason for that (disabling logs isn't a good one)
You can get hostname from spring cloud property in spring-cloud-commons-2.1.0.RC2.jar
environment.getProperty("spring.cloud.client.ip-address");
environment.getProperty("spring.cloud.client.hostname");
spring.factories of spring-cloud-commons-2.1.0.RC2.jar
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor
If you really want your includes method on an ArrayList, just add it:
ArrayList.metaClass.includes = { i -> i in delegate }
Note that -p
is an argument to the mkdir
command specifically, not the whole of Unix. Every command can have whatever arguments it needs.
In this case it means "parents", meaning mkdir
will create a directory and any parents that don't already exist.
The main difference is that WHERE
cannot be used on grouped item (such as SUM(number)
) whereas HAVING
can.
The reason is the WHERE
is done before the grouping and HAVING
is done after the grouping is done.
To set all FormGroup values use, setValue:
this.myFormGroup.setValue({
formControlName1: myValue1,
formControlName2: myValue2
});
To set only some values, use patchValue:
this.myFormGroup.patchValue({
formControlName1: myValue1,
// formControlName2: myValue2 (can be omitted)
});
With this second technique, not all values need to be supplied and fields whos values were not set will not be affected.
Support libraries for ConstraintLayout
could not be installed/updated.
Just open Preferences
> Appearance & Behavior
> System Settings
> Android
and move to SDK Tools
tab. Check the following fields and install.
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]){
int num ;
num = atoi(argv[1]);
printf("\n%d", num);
}
But if your Android App is only for personal purpose or created by you alone, you can use:
me.app_name.app
The best solution we found was to team up with one of those intermediaries. Otherwise you will have to deal with a bunch of other requirements like PCI compliance. We use Verifone's IPCharge and it works quite well.
Give this a try:
Get-ChildItem "C:\Users\gerhardl\Documents\My Received Files" -Filter *.log |
Foreach-Object {
$content = Get-Content $_.FullName
#filter and save content to the original file
$content | Where-Object {$_ -match 'step[49]'} | Set-Content $_.FullName
#filter and save content to a new file
$content | Where-Object {$_ -match 'step[49]'} | Set-Content ($_.BaseName + '_out.log')
}
jquery:
$('div.animalcontent').hide();
$('div').hide();
$('p.animal').bind('mouseover', function() {
$('div.animalcontent').fadeOut();
$('#'+$(this).attr('id')+'content').fadeIn();
});
html:
<p class='animal' id='dog'>dog url</p><div id='dogcontent' class='animalcontent'>Doggiecontent!</div>
<p class='animal' id='cat'>cat url</p><div id='catcontent' class='animalcontent'>Pussiecontent!</div>
<p class='animal' id='snake'>snake url</p><div id='snakecontent'class='animalcontent'>Snakecontent!</div>
-edit-
yeah sure, here you go -- JSFiddle
The answer is in the JavaDoc of the equals()
method:
Unlike
compareTo
, this method considers twoBigDecimal
objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
In other words: equals()
checks if the BigDecimal
objects are exactly the same in every aspect. compareTo()
"only" compares their numeric value.
As to why equals()
behaves this way, this has been answered in this SO question.
I had the same problem today. I tested for four things, some of them already mentioned here:
Are there any values in your child column that don't exist in the parent column (besides NULL, if the child column is nullable)
Do child and parent columns have the same datatype?
Is there an index on the parent column you are referencing? MySQL seems to require this for performance reasons (http://dev.mysql.com/doc/refman/5.5/en/create-table-foreign-keys.html)
And this one solved it for me: Do both tables have identical collation?
I had one table in UTF-8 and the other in iso-something. That didn't work. After changing the iso-table to UTF-8 collation the constraints could be added without problems. In my case, phpMyAdmin didn't even show the child table in iso-encoding in the dropdown for creating the foreign key constraint.
Use include
if you don't mind your script continuing without loading the file (in case it doesn't exist etc) and you can (although you shouldn't) live with a Warning error message being displayed.
Using require
means your script will halt if it can't load the specified file, and throw a Fatal error.
Install cron on Linux/Unix:
apt-get install cron
Use cron on Linux/Unix
crontab -e
See the canonical answer about cron for more details: https://serverfault.com/questions/449651/why-is-my-crontab-not-working-and-how-can-i-troubleshoot-it
Here is how I did to download quickly with cURL (I'm not sure how many files it can download though) :
setlocal EnableDelayedExpansion
cd where\to\download
set STR=
for /f "skip=2 delims=" %%F in ('P:\curl -l -u user:password ftp://ftp.example.com/directory/anotherone/') do set STR=-O "ftp://ftp.example.com/directory/anotherone/%%F" !STR!
path\to\curl.exe -v -u user:password !STR!
Why skip=2 ?
To get ride of .
and ..
Why delims= ? To support names with spaces
This should be
echo date('Y-m-d', strtotime("+30 days"));
strtotime
expects to be given a string containing a US English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
while date
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given.
See the manual pages for
and their function signatures.
There is no way to display interactive elements on the lockscreen or wallpaper with a non jailbroken iPhone.
I would recommend Countdown Widget it's free an you can display countdowns in the notification center which you can also access from your lockscreen.
Problem solved
php artisan cache:clear
sudo chmod -R 777 vendor storage
this enables the write permission to app , framework, logs Hope this will Help
You can try also:
document.body.offsetHeight
document.body.offsetWidth
It does not write to a file by default. You would need to configure something like the RollingFileAppender
and have the root logger write to it (possibly in addition to the default ConsoleAppender
).
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
I found this page very useful
public abstract class GenericDAOWithJPA<T, ID extends Serializable> {
private Class<T> persistentClass;
//This you might want to get injected by the container
protected EntityManager entityManager;
@SuppressWarnings("unchecked")
public GenericDAOWithJPA() {
this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@SuppressWarnings("unchecked")
public List<T> findAll() {
return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
}
}
The project I'm working on, we do something like this. We use the errorlevel
keyword so it kind of looks like:
call myExe.exe
if errorlevel 1 (
goto build_fail
)
That seems to work for us. Note that you can put in multiple commands in the parens like an echo or whatever. Also note that build_fail is defined as:
:build_fail
echo ********** BUILD FAILURE **********
exit /b 1
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
X = iris['data']
y = iris['target']
iris_df = pd.DataFrame(X, columns = iris['feature_names'])
iris_df.head()
You have to pass the route parameters to the route
method, for example:
<li><a href="{{ route('user.profile', $nickname) }}">Profile</a></li>
<li><a href="{{ route('user.settings', $nickname) }}">Settings</a></li>
It's because, both routes have a {nickname}
in the route declaration. I've used $nickname
for example but make sure you change the $nickname
to appropriate value/variable, for example, it could be something like the following:
<li><a href="{{ route('user.settings', auth()->user()->nickname) }}">Settings</a></li>
Modify onClick()
as follows:
@Override
public void onClick(View v) {
if(v == btn) {
canvas=sv.getHolder().lockCanvas();
if(canvas!=null) {
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
} else if(v == btn1) {
saveBitmapToInternalStorage(bitmap);
}
}
There are several ways to enforce that btn
must be pressed before btn1
so that the bitmap
is painted before you attempt to save it.
I suggest that you initially disable btn1
, and that you enable it when btn
is clicked, like this:
if(v == btn) {
...
btn1.setEnabled(true);
}
I don't want to include an external class library project in some of my solutions, so I step into assemblies that I consume in a different way.
My solutions have a "Common Assemblies" directory that contains my own DLLs from other projects. The DLLs that I reference also have their accompanying PDB files for debugging.
In order to debug and set breakpoints, I set a breakpoint in the consuming application's source where I'm calling a method or constructor from the assembly and then step INTO (F11) the method/constructor call.
The debugger will load the assembly's source file in VS and new breakpoints inside of the assembly can be set at that point.
It's not straight forward but works if you don't want to include a new project reference and simply want to reference a shared assembly instead.
Use the set_facecolor(color)
method of the axes
object, which you've created one of the following ways:
You created a figure and axis/es together
fig, ax = plt.subplots(nrows=1, ncols=1)
You created a figure, then axis/es later
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
You used the stateful API (if you're doing anything more than a few lines, and especially if you have multiple plots, the object-oriented methods above make life easier because you can refer to specific figures, plot on certain axes, and customize either)
plt.plot(...)
ax = plt.gca()
Then you can use set_facecolor
:
ax.set_facecolor('xkcd:salmon')
ax.set_facecolor((1.0, 0.47, 0.42))
As a refresher for what colors can be:
matplotlib.colors
Matplotlib recognizes the following formats to specify a color:
- an RGB or RGBA tuple of float values in
[0, 1]
(e.g.,(0.1, 0.2, 0.5)
or(0.1, 0.2, 0.5, 0.3)
);- a hex RGB or RGBA string (e.g.,
'#0F0F0F'
or'#0F0F0F0F'
);- a string representation of a float value in
[0, 1]
inclusive for gray level (e.g.,'0.5'
);- one of
{'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'}
;- a X11/CSS4 color name;
- a name from the xkcd color survey; prefixed with
'xkcd:'
(e.g.,'xkcd:sky blue'
);- one of
{'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'}
which are the Tableau Colors from the ‘T10’ categorical palette (which is the default color cycle);- a “CN” color spec, i.e. 'C' followed by a single digit, which is an index into the default property cycle (
matplotlib.rcParams['axes.prop_cycle']
); the indexing occurs at artist creation time and defaults to black if the cycle does not include color.All string specifications of color, other than “CN”, are case-insensitive.
The easiest thing I can think of is to grab the fingerprint from the debug.keystore (paths are mentioned in other answers) and add that to your project. No need to copy keystores or add new apps. Just append to the list of fingerprints for each machine you develop on.
FWIW, I ran into this when I switched from one laptop to another. I bounce around a lot.
https://support.google.com/firebase/answer/7000104?hl=en#sha1
Hope that helps some folks out! :)
Hmm, there are a few things going wrong here.
for f in os.listdir(src_dir):
os.path.join(src_dir, f)
You're not storing the result of join
. This should be something like:
for f in os.listdir(src_dir):
f = os.path.join(src_dir, f)
This open call is is the cause of your IOError
. (Because without storing the result of the join
above, f
was still just 'file.csv', not 'src_dir/file.csv'.)
Also, the syntax:
with open(f):
is close, but the syntax isn't quite right. It should be with open(file_name) as file_object:
. Then, you use to the file_object
to perform read or write operations.
And finally:
write(line)
You told python what you wanted to write, but not where to write it. Write is a method on the file object. Try file_object.write(line)
.
Edit: You're also clobbering your input file. You probably want to open
the output file and write lines to it as you're reading them in from the input file.
See: input / output in python.
Since none of them all worked for me (select2 4.0.3) is went the std select way.
for(var i = selectbox.options.length - 1 ; i >= 0 ; i--)
selectbox.remove(i);
You can loop through the table variable or you can cursor through it. This is what we usually call a RBAR - pronounced Reebar and means Row-By-Agonizing-Row.
I would suggest finding a SET-BASED answer to your question (we can help with that) and move away from rbars as much as possible.
Your old ugly style is automatically compiled by JAVAC 1.6 as :
StringBuilder sb = new StringBuilder("What do you get if you multiply ");
sb.append(varSix);
sb.append(" by ");
sb.append(varNine);
sb.append("?");
String s = sb.toString();
So there is absolutely no difference between this and using a StringBuilder.
String.format is a lot more heavyweight since it creates a new Formatter, parses your input format string, creates a StringBuilder, append everything to it and calls toString().
There's a facility to have a separate style sheet for print, using
<link type="text/css" rel="stylesheet" media="print" href="print.css">
I don't know if it does what you want though.
Basically mentioned this in pyserial documentation https://pyserial.readthedocs.io/en/latest/tools.html#module-serial.tools.list_ports
import serial.tools.list_ports
ports = serial.tools.list_ports.comports()
for port, desc, hwid in sorted(ports):
print("{}: {} [{}]".format(port, desc, hwid))
Result :
COM1: Communications Port (COM1) [ACPI\PNP0501\1]
COM7: MediaTek USB Port (COM7) [USB VID:PID=0E8D:0003 SER=6 LOCATION=1-2.1]
The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.
$env:USERPROFILE = "C:\\Documents and Settings\\[USER]\\"
dom event delegation is something different from the computer science definition.
It refers to handling bubbling events from many elements, like table cells, from a parent object, like the table. It can keep the code simpler, especially when adding or removing elements, and saves some memory.
InitialValue="0" : initial validation will fire when 0th index item is selected in ddl.
<asp:RequiredFieldValidator InitialValue="0" Display="Dynamic" CssClass="error" runat="server" ID="your_id" ValidationGroup="validationgroup" ControlToValidate="your_dropdownlist_id" />
It looks like the JavaScript error your getting is probably being caused by
password: {
required:true,
rangelenght:[4.20]
},
As the [4.20]
should be [4,20]
, which i'd guess is throwing off the validation code in additional-methods
hence giving the type error's you posted.
Edit: As others have noted in the below comments rangelenght
is also misspelled & jquery.validate.js
library appears to be missing (assuming its not compiled in to one of your other assets)
#The Best way is to use `fStrings` (very easy and powerful in python3)
#Format: f'your-string'
#For Example:
mylist=['laks',444,'M']
cursor.execute(f'INSERT INTO mytable VALUES ("{mylist[0]}","{mylist[1]}","{mylist[2]}")')
#THATS ALL!! EASY!!
#You can use it with for loop!
Generally speaking, it's recommended to use MSI-based installations on Windows. Thus, if you're ready to invest a fair bit of time, WiX is the way to go.
If you want something which is much more simpler, go with InnoSetup.
I found this by adapting some tutos. Thanks to google, and to all of you ;)
def findall(L, test):
i=0
indices = []
while(True):
try:
# next value in list passing the test
nextvalue = filter(test, L[i:])[0]
# add index of this value in the index list,
# by searching the value in L[i:]
indices.append(L.index(nextvalue, i))
# iterate i, that is the next index from where to search
i=indices[-1]+1
#when there is no further "good value", filter returns [],
# hence there is an out of range exeption
except IndexError:
return indices
A very simple use:
a = [0,0,2,1]
ind = findall(a, lambda x:x>0))
[2, 3]
P.S. scuse my english
If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.
public new IEnumerator<T> GetEnumerator()
{
return this.Values.GetEnumerator();
}
String.contains
works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.
Note that String.contains
does not check for word boundary; it simply checks for substring.
Regex is more powerful than String.contains
, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.
Use String.matches
with the following regex:
"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"
The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above):
(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*
The \b
checks for word boundary, so that you don't get a match for restores store products
. Note that stores 3store_product
is also rejected, since digit and _
are considered part of a word, but I doubt this case appear in natural text.
Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product
will not match the regex above, since you are searching for the word store
without s
.
.
normally match any character except a number of new line characters. (?s)
at the beginning makes .
matches any character without exception (thanks to Tim Pietzcker for pointing this out).
What's the column "BIO" datatype? What database server (sql/oracle/mysql)? You should be able to span over multiple lines all you want as long as you adhere to the character limit in the column's datatype (ie: varchar(200) ). Try using single quotes, that might make a difference. This works for me:
update table set mycolumn = 'hello world,
my name is carlos.
goodbye.'
where id = 1;
Also, you might want to put in checks for single quotes if you are concatinating the sql string together in C#. If the variable contains single quotes that could escape the code out of the sql statement, therefore, not doing all the lines you were expecting to see.
BTW, you can delimit your SQL statements with a semi colon like you do in C#, just as FYI.
For me, a hint to wrap the troubled element in another HTML tag helped. However I also needed to add a key to that HTML tag. For example:
// Didn't work
<div>
<TroubledComponent/>
</div>
// Worked
<div key='uniqueKey'>
<TroubledComponent/>
</div>
HERE=$(cd $(dirname $BASH_SOURCE) && pwd)
where you get the full path with new_path=$(dirname ${BASH_SOURCE[0]})
. You change current directory with cd
new_path and then run pwd
to get the full path to the current directory.
I was tinkering around when moving our applications to HTML5 with RESTful apis in the backend. The solution that I came up with was:
As you can see, this reduces the frequent refresh token requests. If user closes the browser/app before the renew token call is triggered, the previous token will expire in time and user will have to re-login.
A more complicated strategy can be implemented to cater for user inactivity (e.g. neglected an opened browser tab). In that case, the renew token call should include the expected expiring time which should not exceed the defined session time. The application will have to keep track of the last user interaction accordingly.
I don't like the idea of setting long expiration hence this approach may not work well with native applications requiring less frequent authentication.
function myYmd(D){_x000D_
var pad = function(num) {_x000D_
var s = '0' + num;_x000D_
return s.substr(s.length - 2);_x000D_
}_x000D_
var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate());_x000D_
return Result;_x000D_
}_x000D_
_x000D_
var datemilli = new Date('Sun May 11,2014');_x000D_
document.write(myYmd(datemilli));
_x000D_
As per this link you may also have to prefix your param with &rp if not using proxy syntax
What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.
Use df[df['B']==3]['A'].values
if you just want item itself without the brackets
You need a parameterless constructor to be able to create an instance of your class. Your current constructor requires two input string parameters.
Normally C++ implies having such a constructor (=default parameterless constructor) if there is no other constructor declared. By declaring your first constructor with two parameters you overwrite this default behaviour and now you have to declare this constructor explicitly.
Here is the working code:
#include <iostream>
#include <string> // <-- you need this if you want to use string type
using namespace std;
class name {
public:
string first;
string last;
name(string a, string b){
first = a;
last = b;
}
name () // <-- this is your explicit parameterless constructor
{}
};
int main (int argc, const char * argv[])
{
const int howManyNames = 3;
name someName[howManyNames];
return 0;
}
(BTW, you need to include to make the code compilable.)
An alternative way is to initialize your instances explicitly on declaration
name someName[howManyNames] = { {"Ivan", "The Terrible"}, {"Catherine", "The Great"} };
Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:
USE [master];
GO
CREATE LOGIN MyNewAdminUser
WITH PASSWORD = N'abcd',
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember
@loginame = N'MyNewAdminUser',
@rolename = N'sysadmin';
You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).
swift solution
yourlabel.text = yourvariable
or self is use for when you are in async {brackets} or in some Extension
DispatchQueue.main.async{
self.yourlabel.text = "typestring"
}
function _cron_exe($schedules) {
if ($obj->get_option('cronenabledisable') == "yes") {
// $interval = 1*20;
$interval = $obj->get_option('cronhowtime');
if ($obj->get_option('crontiming') == 'minutes') {
$interval = $interval * 60;
} else if ($obj->get_option('crontiming') == 'hours') {
$interval = $interval * 3600;
} else if ($obj->get_option('crontiming') == 'days') {
$interval = $interval * 86400;
}
$schedules['hourlys'] = array(
'interval' => $interval,
'display' => 'cronjob'
);
return $schedules;
}
}
Use the -H
header again before the Authorization:Basic things. So it will be
curl -i \
-H 'Accept:application/json' \
-H 'Authorization:Basic BASE64_string' \
http://example.com
Here, BASE64_string
= Base64 of username:password
NSArray *array1 = [NSArray arrayWithObjects:@"todd1", @"todd2", @"todd3", nil];
bool objectMembership = [array1 containsObject:@"todd1"];
NSLog(@"%d",objectMembership); // prints 1 or 0
For Centos 7 Use below command to install Python Development Package
Python 2.7
sudo yum install python-dev
Python 3.4
sudo yum install python34-devel
Still if your problem not solved then try installing below packages -
sudo yum install libffi-devel
sudo yum install openssl-devel
Detecting browser's details:
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>'
)
Source JavaScript: browser name.
See JSFiddle to detect Browser Details.
Detecting OS:
// This script sets OSName variable as follows:
// "Windows" for all versions of Windows
// "MacOS" for all versions of Macintosh OS
// "Linux" for all versions of Linux
// "UNIX" for all other UNIX flavors
// "Unknown OS" indicates failure to detect the OS
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
document.write('Your OS: '+OSName);
source JavaScript: OS detection.
See JSFiddle to detect OS Details.
var nVer = navigator.appVersion;_x000D_
var nAgt = navigator.userAgent;_x000D_
var browserName = navigator.appName;_x000D_
var fullVersion = ''+parseFloat(navigator.appVersion); _x000D_
var majorVersion = parseInt(navigator.appVersion,10);_x000D_
var nameOffset,verOffset,ix;_x000D_
_x000D_
// In Opera, the true version is after "Opera" or after "Version"_x000D_
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {_x000D_
browserName = "Opera";_x000D_
fullVersion = nAgt.substring(verOffset+6);_x000D_
if ((verOffset=nAgt.indexOf("Version"))!=-1) _x000D_
fullVersion = nAgt.substring(verOffset+8);_x000D_
}_x000D_
// In MSIE, the true version is after "MSIE" in userAgent_x000D_
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {_x000D_
browserName = "Microsoft Internet Explorer";_x000D_
fullVersion = nAgt.substring(verOffset+5);_x000D_
}_x000D_
// In Chrome, the true version is after "Chrome" _x000D_
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {_x000D_
browserName = "Chrome";_x000D_
fullVersion = nAgt.substring(verOffset+7);_x000D_
}_x000D_
// In Safari, the true version is after "Safari" or after "Version" _x000D_
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {_x000D_
browserName = "Safari";_x000D_
fullVersion = nAgt.substring(verOffset+7);_x000D_
if ((verOffset=nAgt.indexOf("Version"))!=-1) _x000D_
fullVersion = nAgt.substring(verOffset+8);_x000D_
}_x000D_
// In Firefox, the true version is after "Firefox" _x000D_
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {_x000D_
browserName = "Firefox";_x000D_
fullVersion = nAgt.substring(verOffset+8);_x000D_
}_x000D_
// In most other browsers, "name/version" is at the end of userAgent _x000D_
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < _x000D_
(verOffset=nAgt.lastIndexOf('/')) ) _x000D_
{_x000D_
browserName = nAgt.substring(nameOffset,verOffset);_x000D_
fullVersion = nAgt.substring(verOffset+1);_x000D_
if (browserName.toLowerCase()==browserName.toUpperCase()) {_x000D_
browserName = navigator.appName;_x000D_
}_x000D_
}_x000D_
// trim the fullVersion string at semicolon/space if present_x000D_
if ((ix=fullVersion.indexOf(";"))!=-1)_x000D_
fullVersion=fullVersion.substring(0,ix);_x000D_
if ((ix=fullVersion.indexOf(" "))!=-1)_x000D_
fullVersion=fullVersion.substring(0,ix);_x000D_
_x000D_
majorVersion = parseInt(''+fullVersion,10);_x000D_
if (isNaN(majorVersion)) {_x000D_
fullVersion = ''+parseFloat(navigator.appVersion); _x000D_
majorVersion = parseInt(navigator.appVersion,10);_x000D_
}_x000D_
_x000D_
document.write(''_x000D_
+'Browser name = '+browserName+'<br>'_x000D_
+'Full version = '+fullVersion+'<br>'_x000D_
+'Major version = '+majorVersion+'<br>'_x000D_
+'navigator.appName = '+navigator.appName+'<br>'_x000D_
+'navigator.userAgent = '+navigator.userAgent+'<br>'_x000D_
)_x000D_
_x000D_
// This script sets OSName variable as follows:_x000D_
// "Windows" for all versions of Windows_x000D_
// "MacOS" for all versions of Macintosh OS_x000D_
// "Linux" for all versions of Linux_x000D_
// "UNIX" for all other UNIX flavors _x000D_
// "Unknown OS" indicates failure to detect the OS_x000D_
_x000D_
var OSName="Unknown OS";_x000D_
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";_x000D_
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";_x000D_
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";_x000D_
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";_x000D_
_x000D_
document.write('Your OS: '+OSName);
_x000D_
background-position-x: center;
background-position-y: center;
This works recursively for infinitely nested elements:
def iterFlatten(root):
if isinstance(root, (list, tuple)):
for element in root:
for e in iterFlatten(element):
yield e
else:
yield root
Result:
>>> b = [["a", ("b", "c")], "d"] >>> list(iterFlatten(b)) ['a', 'b', 'c', 'd']
Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.
Here is an example in C#. Create four classes within a console application:
public abstract class Vehicle
{
public abstract int Wheels;
}
public class Bicycle : Vehicle
{
public override int Wheels()
{
return 2;
}
}
public class Car : Vehicle
{
public override int Wheels()
{
return 4;
}
}
public class Truck : Vehicle
{
public override int Wheels()
{
return 18;
}
}
Now create the following in the Main() of the module for the console application:
public void Main()
{
List<Vehicle> vehicles = new List<Vehicle>();
vehicles.Add(new Bicycle());
vehicles.Add(new Car());
vehicles.Add(new Truck());
foreach (Vehicle v in vehicles)
{
Console.WriteLine(
string.Format("A {0} has {1} wheels.",
v.GetType().Name, v.Wheels));
}
}
In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.
We then add a Bicycle, Car and Truck to the list.
Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.
This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.
I hope that this helps you.
It's now 2018, and we finally have cheap ways to do something around it...
Indeed, since the 2d context API now has a filter
property, and that this filter property can accept SVGFilters, we can build an SVGFilter that will keep only fully opaque pixels from our drawings, and thus eliminate the default anti-aliasing.
So it won't deactivate antialiasing per se, but provides a cheap way both in term of implementation and of performances to remove all semi-transparent pixels while drawing.
I am not really a specialist of SVGFilters, so there might be a better way of doing it, but for the example, I'll use a <feComponentTransfer>
node to grab only fully opaque pixels.
var ctx = canvas.getContext('2d');_x000D_
ctx.fillStyle = '#ABEDBE';_x000D_
ctx.fillRect(0,0,canvas.width,canvas.height);_x000D_
ctx.fillStyle = 'black';_x000D_
ctx.font = '14px sans-serif';_x000D_
ctx.textAlign = 'center';_x000D_
_x000D_
// first without filter_x000D_
ctx.fillText('no filter', 60, 20);_x000D_
drawArc();_x000D_
drawTriangle();_x000D_
// then with filter_x000D_
ctx.setTransform(1, 0, 0, 1, 120, 0);_x000D_
ctx.filter = 'url(#remove-alpha)';_x000D_
// and do the same ops_x000D_
ctx.fillText('no alpha', 60, 20);_x000D_
drawArc();_x000D_
drawTriangle();_x000D_
_x000D_
// to remove the filter_x000D_
ctx.filter = 'none';_x000D_
_x000D_
_x000D_
function drawArc() {_x000D_
ctx.beginPath();_x000D_
ctx.arc(60, 80, 50, 0, Math.PI * 2);_x000D_
ctx.stroke();_x000D_
}_x000D_
_x000D_
function drawTriangle() {_x000D_
ctx.beginPath();_x000D_
ctx.moveTo(60, 150);_x000D_
ctx.lineTo(110, 230);_x000D_
ctx.lineTo(10, 230);_x000D_
ctx.closePath();_x000D_
ctx.stroke();_x000D_
}_x000D_
// unrelated_x000D_
// simply to show a zoomed-in version_x000D_
var zCtx = zoomed.getContext('2d');_x000D_
zCtx.imageSmoothingEnabled = false;_x000D_
canvas.onmousemove = function drawToZoommed(e) {_x000D_
var x = e.pageX - this.offsetLeft,_x000D_
y = e.pageY - this.offsetTop,_x000D_
w = this.width,_x000D_
h = this.height;_x000D_
_x000D_
zCtx.clearRect(0,0,w,h);_x000D_
zCtx.drawImage(this, x-w/6,y-h/6,w, h, 0,0,w*3, h*3);_x000D_
}
_x000D_
<svg width="0" height="0" style="position:absolute;z-index:-1;">_x000D_
<defs>_x000D_
<filter id="remove-alpha" x="0" y="0" width="100%" height="100%">_x000D_
<feComponentTransfer>_x000D_
<feFuncA type="discrete" tableValues="0 1"></feFuncA>_x000D_
</feComponentTransfer>_x000D_
</filter>_x000D_
</defs>_x000D_
</svg>_x000D_
_x000D_
<canvas id="canvas" width="250" height="250" ></canvas>_x000D_
<canvas id="zoomed" width="250" height="250" ></canvas>
_x000D_
And for the ones that don't like to append an <svg>
element in their DOM, you can also save it as an external svg file and set the filter
property to path/to/svg_file.svg#remove-alpha
.
This is the better solution:
verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));
On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:
{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}
I had the same problem, it was a missing manifest.json file, if not found the browser decide with orientation is best fit, if you don't specify the file or use a wrong path.
I fixed just calling the manifest.json correctly on html headers.
My html headers:
<meta name="application-name" content="App Name">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="manifest" href="manifest.json">
<meta name="msapplication-starturl" content="/">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#">
<meta name="msapplication-TileColor" content="#">
<meta name="msapplication-config" content="browserconfig.xml">
<link rel="icon" type="image/png" sizes="192x192" href="android-chrome-192x192.png">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
<link rel="mask-icon" href="safari-pinned-tab.svg" color="#ffffff">
<link rel="shortcut icon" href="favicon.ico">
And the manifest.json file content:
{
"display": "standalone",
"orientation": "portrait",
"start_url": "/",
"theme_color": "#000000",
"background_color": "#ffffff",
"icons": [
{
"src": "android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
}
}
To generate your favicons and icons use this webtool: https://realfavicongenerator.net/
To generate your manifest file use: https://tomitm.github.io/appmanifest/
My PWA Works great, hope it helps!
For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:
.field-error {_x000D_
color: #f44336;_x000D_
padding: 2px 5px;_x000D_
position: absolute;_x000D_
font-size: small;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
-moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
-webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
-o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
from { background-color: lightgreen; } /** from color **/_x000D_
to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
Bdizzle,
I would recommend that you read this link
You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.
Be happy, Julian
Even I had same problem
Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/]
I have added respective dependency at very begenining it had worked for me.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
The original question concerns infinity. So, why not use
#define Infinity ((double)(42 / 0.0))
according to the IEEE definition? You can negate that of course.
Folowing Nitin Bansal's answer
and for even more robustness:
function getIframeWindow(iframe_object) {
var doc;
if (iframe_object.contentWindow) {
return iframe_object.contentWindow;
}
if (iframe_object.window) {
return iframe_object.window;
}
if (!doc && iframe_object.contentDocument) {
doc = iframe_object.contentDocument;
}
if (!doc && iframe_object.document) {
doc = iframe_object.document;
}
if (doc && doc.defaultView) {
return doc.defaultView;
}
if (doc && doc.parentWindow) {
return doc.parentWindow;
}
return undefined;
}
and
...
var el = document.getElementById('targetFrame');
var frame_win = getIframeWindow(el);
if (frame_win) {
frame_win.targetFunction();
...
}
...
Well, you don't specify if it's a 32 or 64 bit dll and you don't include the error message, but I'll guess that it's the same issue as described in this KB article: Error Message When You Run Regsvr32.exe on 64-Bit Windows
Quote from that article:
This behavior occurs because the Regsvr32.exe file in the System32 folder is a 64-bit version. When you run Regsvr32 to register a DLL, you are using the 64-bit version by default.
Solution from that article:
To resolve this issue, run Regsvr32.exe from the %SystemRoot%\Syswow64 folder. For example, type the following commands to register the DLL:
cd \windows\syswow64
regsvr32 c:\filename.dll
Once you find the term you need to remove it from String under process so that it won't resolve the same again, use indexOf()
and substring()
, you don't need to do contains check length times
Most SSL certificates are bound to the hostname of the machine and not the ip address.
You might get a better answer if you ask this question on serverfault.com
git mv
moves the file, updating the index to record the replaced file path, as well as updating any affected git submodules. Unlike a manual move, it also detects case-only renames that would not otherwise be detected as a change by git.
It is similar (though not identical) in behavior to moving the file externally to git, removing the old path from the index using git rm
, and adding the new one to the index using git add
.
This question has a lot of great partial answers. This answer is an attempt to combine them into a single cohesive answer. Additionally, one thing not called out by any of the other answers is the fact that the man page actually does mostly answer the question, but it's perhaps less obvious than it could be.
Three different effects are called out in the man page:
The file, directory, or symlink is moved in the filesystem:
git-mv - Move or rename a file, a directory, or a symlink
The index is updated, adding the new path and removing the previous one:
The index is updated after successful completion, but the change must still be committed.
Moved submodules are updated to work at the new location:
Moving a submodule using a gitfile (which means they were cloned with a Git version 1.7.8 or newer) will update the gitfile and core.worktree setting to make the submodule work in the new location. It also will attempt to update the submodule.<name>.path setting in the gitmodules(5) file and stage that file (unless -n is used).
As mentioned in this answer, git mv
is very similar to moving the file, adding the new path to the index, and removing the previous path from the index:
mv oldname newname
git add newname
git rm oldname
However, as this answer points out, git mv
is not strictly identical to this in behavior. Moving the file via git mv
adds the new path to the index, but not any modified content in the file. Using the three individual commands, on the other hand, adds the entire file to the index, including any modified content. This could be relevant when using a workflow which patches the index, rather than adding all changes in the file.
Additionally, as mentioned in this answer and this comment, git mv
has the added benefit of handling case-only renames on file systems that are case-insensitive but case-preserving, as is often the case in current macOS and Windows file systems. For example, in such systems, git would not detect that the file name has changed after moving a file via mv Mytest.txt MyTest.txt
, whereas using git mv Mytest.txt MyTest.txt
would successfully update its name.
Here's an example where the absence of b
would throw a TypeError
exception in Python 3.x
>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
Adding a b
prefix would fix the problem.
First change the array to a string by using implode() function. E.g $number=array(1,2,3,4,5,...);
$stringofnumber=implode("|",$number);
then pass the string to a session. e.g $_SESSION['string']=$stringofnumber;
so when you go to the page where you want to use the array, just explode your string. e.g
$number=explode("|", $_SESSION['string']);
finally number is your array but remember to start array on the of each page.
I guess you've meant:
[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
This would be sorted like this:
sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))
A solution, can be:
with open("file", "r") as fd:
lines = fd.read().splitlines()
You get the list of lines without "\r\n" or "\n".
Or, use the classic way:
with open("file", "r") as fd:
for line in fd:
line = line.strip()
You read the file, line by line and drop the spaces and newlines.
If you only want to drop the newlines:
with open("file", "r") as fd:
for line in fd:
line = line.replace("\r", "").replace("\n", "")
Et voilà.
Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open
.
See the documentation of io.open.
So, you can use:
with io.open("file", "r", newline=None) as fd:
for line in fd:
line = line.replace("\n", "")
When the newline parameter is None
: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.
newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
Adding to the @htafoya answer. The code snippet will be
const getTimeEpoch = () => {
return new Date().getTime().toString();
}
Looks like you need the package from the installation media if you're you're offline (located at D:\sources\sxs
) You could copy this to each machine that you require .NET 3.5 on (so technically you only need the installation media once to get the package) and get each machine to run the command:
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
There's a guide on MSDN.
Pushing and popping registers are behind the scenes equivalent to this:
push reg <= same as => sub $8,%rsp # subtract 8 from rsp
mov reg,(%rsp) # store, using rsp as the address
pop reg <= same as=> mov (%rsp),reg # load, using rsp as the address
add $8,%rsp # add 8 to the rsp
Note this is x86-64 At&t syntax.
Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.