Another, less convenient, way to do it is to use Decimal
class:
from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')
I'm a beginner in Java...
I found another implementation for the infinity in the Java documentation, for the boolean
and double
types.
https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3
Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity.
It looks ugly, but it works.
public class Main {
public static void main(String[] args) {
System.out.println(1.0/0.0);
System.out.println(-1.0/0.0);
}
}
Like ?egDwight said, you can use the HTML entity &infin
; or ∞
. A easy source of getting these codes, is to look at this entity list.
You can also use them in CSS, which was what I was looking for, just like font-awesome does. A simple CSS based solution would be to have something like:
.infinity-ico:before {
content: '\221E';
}
Integers are inherently finite. The closest you can get is by setting a
to int
's maximum value:
#include <limits>
// ...
int a = std::numeric_limits<int>::max();
Which would be 2^31 - 1
(or 2 147 483 647
) if int
is 32 bits wide on your implementation.
If you really need infinity, use a floating point number type, like float
or double
. You can then get infinity with:
double a = std::numeric_limits<double>::infinity();
So does C99.
The IEEE 754 floating point representation used by all modern processors has several special bit patterns reserved for positive infinity (sign=0, exp=~0, frac=0), negative infinity (sign=1, exp=~0, frac=0), and many NaN (Not a Number: exp=~0, frac?0).
All you need to worry about: some arithmetic may cause floating point exceptions/traps, but those aren't limited to only these "interesting" constants.
Yes,
basically when we write
i += l;
the compiler converts this to
i = (int)(i + l);
I just checked the .class
file code.
Really a good thing to know
The -nc
, --no-clobber
option isn't the best solution as newer files will not be downloaded. One should use -N
instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:
wget -N http://www.example.com/images/misc/pic.png
Then running Wget with -N, with or without
-r
or-p
, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file.-nc
may not be specified at the same time as-N
.
-N
,--timestamping
: Turn on time-stamping.
Use the Integer
wrapper class instead of String because it is doing the hard work for you by implementing Comparable<Integer>
. Then java.util.Collections.sort(list);
would do the trick.
I'm starting to learn about this myself, being very new to android development and I found this video very helpful.
https://www.youtube.com/watch?v=qcotbMLjlA4
It specifically covers to to get JSONArray to JSONObject at 19:30 in the video.
Code from the video for JSONArray to JSONObject:
JSONArray queryArray = quoteJSONObject.names();
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < queryArray.length(); i++){
list.add(queryArray.getString(i));
}
for(String item : list){
Log.v("JSON ARRAY ITEMS ", item);
}
I am using wamp64 on my windows 10 machine. I was having the same issue and turning off Xdebug of from my php.ini file resolves the issue for me.
; [xdebug]
; zend_extension ="C:/wamp64/bin/php/php5.6.25/zend_ext/php_xdebug-2.4.1-5.6-vc11-x86_64.dll"
; xdebug.remote_enable = off
; xdebug.profiler_enable = off
; xdebug.profiler_enable_trigger = off
; xdebug.profiler_output_name = cachegrind.out.%t.%p
; xdebug.profiler_output_dir ="C:/wamp64/tmp"
; xdebug.show_local_vars=0
If you want an argument that might appeal to a boss: Think about what a URL is. URLs are public. People copy and paste them. They share them, they put them on advertisements. Nothing prevents someone (knowingly or not) from mailing that URL around for other people to use. If your API key is in that URL, everybody has it.
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
I think what you are looking for is as follows.
cars_by_cylinders_gears <- mtcars %>%
group_by(cyl, gear) %>%
summarise(count = n())
This is using the dplyr package. This is essentially the longhand version of the count () solution provided by docendo discimus.
just put #login-box
before <h2>Welcome</h2>
will be ok.
<div class='container'>
<div class='hero-unit'>
<div id='login-box' class='pull-right control-group'>
<div class='clearfix'>
<input type='text' placeholder='Username' />
</div>
<div class='clearfix'>
<input type='password' placeholder='Password' />
</div>
<button type='button' class='btn btn-primary'>Log in</button>
</div>
<h2>Welcome</h2>
<p>Please log in</p>
</div>
</div>
here is jsfiddle http://jsfiddle.net/SyjjW/4/
It far easier to use the scripting runtime which is installed by default on Windows
Just go project Reference and check Microsoft Scripting Runtime and click OK.
Then you can use this code which is way better than the default file commands
Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis", ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
TempS = TS.ReadLine
Final = Final & TempS & vbCrLf
Loop
TS.Close
Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt", ForWriting, True)
TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing
As for what is wrong with your original code here you are reading each line of the text file.
Input #iFileNo, sFileText
Then here you write it out
Write #iFileNo, sFileText
sFileText is a string variable so what is happening is that each time you read, you just replace the content of sFileText with the content of the line you just read.
So when you go to write it out, all you are writing is the last line you read, which is probably a blank line.
Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo
iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo, sFinal
Close #iFileNo
Note you don't need to do a loop to write. sFinal contains the complete text of the File ready to be written at one shot. Note that input reads a LINE at a time so each line appended to sFinal needs to have a CR and LF appended at the end to be written out correctly on a MS Windows system. Other operating system may just need a LF (Chr$(10)).
If you need to process the incoming data then you need to do something like this.
Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
C.Add sFileText
Loop
Close #iFileNo
For Each vTemp in C
Process vTemp
Next sTemp
iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
Write #iFileNo, vTemp & vbCRLF
Next sTemp
Close #iFileNo
Off the top of my head, the following are the only built-ins that are subscriptable:
string: "foobar"[3] == "b"
tuple: (1,2,3,4)[3] == 4
list: [1,2,3,4][3] == 4
dict: {"a":1, "b":2, "c":3}["c"] == 3
But mipadi's answer is correct - any class that implements __getitem__
is subscriptable
Go to File > Settings > Builds,Execution,Deployment > Build Tools > Gradle >Gradle home path
Now, set Use default gradle wrapper and edit Project\gradle\wrapper\gradle-wrapper.properties files field distributionUrl like this
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip
in you aspx file you should put the first line as this :
<%@ Page EnableEventValidation="false" %>
if you already have something like <%@ Page
so just add the rest => EnableEventValidation="false" %>
I recommend not to do it.
To avoid potentially unexpected results when using GROUP BY
without an aggregate function, as is used in the accepted answer, because MySQL is free to retrieve ANY value within the data set being grouped when not using an aggregate function [sic] and issues with ONLY_FULL_GROUP_BY
. Please consider using an exclusion join.
Assuming the firstname and lastname are uniquely indexed (unambiguous), an alternative to GROUP BY
is to sort using a LEFT JOIN
to filter the result set, otherwise known as an exclusion JOIN.
Ascending order (A-Z)
To retrieve the distinct firstname ordered by lastname from A-Z
Query
SELECT t1.*
FROM table_name AS t1
LEFT JOIN table_name AS t2
ON t1.firstname = t2.firstname
AND t1.lastname > t2.lastname
WHERE t2.id IS NULL;
Result
| id | firstname | lastname |
|----|-----------|----------|
| 2 | Bugs | Bunny |
| 1 | John | Doe |
Descending order (Z-A)
To retrieve the distinct firstname ordered by lastname from Z-A
Query
SELECT t1.*
FROM table_name AS t1
LEFT JOIN table_name AS t2
ON t1.firstname = t2.firstname
AND t1.lastname < t2.lastname
WHERE t2.id IS NULL;
Result
| id | firstname | lastname |
|----|-----------|----------|
| 2 | Bugs | Bunny |
| 3 | John | Johnson |
You can then order the resulting data as desired.
If the first and last name combination are not unique (ambiguous) and you have multiple rows of the same values, you can filter the result set by including an OR condition on the JOIN criteria to also filter by id.
table_name data
(1, 'John', 'Doe'),
(2, 'Bugs', 'Bunny'),
(3, 'John', 'Johnson'),
(4, 'John', 'Doe'),
(5, 'John', 'Johnson')
Query
SELECT t1.*
FROM table_name AS t1
LEFT JOIN table_name AS t2
ON t1.firstname = t2.firstname
AND (t1.lastname > t2.lastname
OR (t1.firstname = t1.firstname AND t1.lastname = t2.lastname AND t1.id > t2.id))
WHERE t2.id IS NULL;
Result
| id | firstname | lastname |
|----|-----------|----------|
| 1 | John | Doe |
| 2 | Bugs | Bunny |
EDIT
My original answer using an ordered subquery, was written prior to MySQL 5.7.5, which is no longer applicable, due to the changes with ONLY_FULL_GROUP_BY
. Please use the exclusion join examples above instead.
It is also important to note; when ONLY_FULL_GROUP_BY
is disabled (original behavior prior to MySQL 5.7.5), the use of GROUP BY
without an aggregate function may yield unexpected results, because MySQL is free to choose ANY value within the data set being grouped [sic].
Meaning an ID
or lastname
value may be retrieved that is not associated with the retrieved firstname
row.
WARNING
With MySQL GROUP BY
may not yield the expected results when used with ORDER BY
The best method of implementation, to ensure expected results, is to filter the result set scope using an ordered subquery.
table_name data
(1, 'John', 'Doe'),
(2, 'Bugs', 'Bunny'),
(3, 'John', 'Johnson')
Query
SELECT * FROM (
SELECT * FROM table_name ORDER BY ID DESC
) AS t1
GROUP BY FirstName
Result
| ID | first | last |
|----|-------|---------|
| 2 | Bugs | Bunny |
| 3 | John | Johnson |
Comparison
To demonstrate the unexpected results when using GROUP BY
in combination with ORDER BY
Query
SELECT * FROM table_name GROUP BY FirstName ORDER BY ID DESC
Result
| ID | first | last |
|----|-------|-------|
| 2 | Bugs | Bunny |
| 1 | John | Doe |
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
$ svn copy http://svn.example.com/repos/calc/trunk@192 \
http://svn.example.com/repos/calc/branches/my-calc-branch \
-m "Creating a private branch of /calc/trunk."
Where 192 is the revision you specify
You can find this information from the SVN Book, specifically here on the page about svn copy
Page -- Takes the specified XAML file, and compiles into BAML, and embeds that output into the managed resource stream for your assembly (specifically AssemblyName.g.resources), Additionally, if you have the appropriate attributes on the root XAML element in the file, it will create a blah.g.cs file, which will contain a partial class of the "codebehind" for that page; this basically involves a call to the BAML goop to re-hydrate the file into memory, and to set any of the member variables of your class to the now-created items (e.g. if you put x:Name="foo" on an item, you'll be able to do this.foo.Background = Purple; or similar.
ApplicationDefinition -- similar to Page, except it goes onestep furthur, and defines the entry point for your application that will instantiate your app object, call run on it, which will then instantiate the type set by the StartupUri property, and will give your mainwindow.
Also, to be clear, this question overall is infinate in it's results set; anyone can define additional BuildActions just by building an MSBuild Task. If you look in the %systemroot%\Microsoft.net\framework\v{version}\ directory, and look at the Microsoft.Common.targets file, you should be able to decipher many more (example, with VS Pro and above, there is a "Shadow" action that allows you generate private accessors to help with unit testing private classes.
You could also use vbCrLf
which corresponds to Chr(13)
& Chr(10)
.
Below is code that I currently use to pull data from a MS SQL Server 2008 into VBA. You need to make sure you have the proper ADODB reference [VBA Editor->Tools->References] and make sure you have Microsoft ActiveX Data Objects 2.8 Library checked, which is the second from the bottom row that is checked (I'm using Excel 2010 on Windows 7; you might have a slightly different ActiveX version, but it will still begin with Microsoft ActiveX):
Sub Module for Connecting to MS SQL with Remote Host & Username/Password
Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
'Setup the connection string for accessing MS SQL database
'Make sure to change:
'1: PASSWORD
'2: USERNAME
'3: REMOTE_IP_ADDRESS
'4: DATABASE
ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"
'Opens connection to the database
cnn.Open ConnectionString
'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
cnn.CommandTimeout = 900
'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
StrQuery = "SELECT TOP 10 * FROM tbl_table"
'Performs the actual query
rst.Open StrQuery, cnn
'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
Sheets(1).Range("A2").CopyFromRecordset rst
End Sub
Pickle is probably the best option, but in case anyone wonders how to save and load a dictionary to a file using NumPy:
import numpy as np
# Save
dictionary = {'hello':'world'}
np.save('my_file.npy', dictionary)
# Load
read_dictionary = np.load('my_file.npy',allow_pickle='TRUE').item()
print(read_dictionary['hello']) # displays "world"
FYI: NPY file viewer
Swift Version of Simon Lee's answer .
// MARK: - Variables
var isCcBccSelected = false // To toggle Bcc.
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// Hide the Bcc Text Field , until CC gets focused in didSelectRowAtIndexPath()
if self.cellTypes[indexPath.row] == CellType.Bcc {
if (isCcBccSelected) {
return 44
} else {
return 0
}
}
return 44.0
}
Then in didSelectRowAtIndexPath()
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
// To Get the Focus of CC, so that we can expand Bcc
if self.cellTypes[indexPath.row] == CellType.Cc {
if let cell = tableView.cellForRowAtIndexPath(indexPath) as? RecipientTableViewCell {
if cell.tag == 1 {
cell.recipientTypeLabel.text = "Cc:"
cell.recipientTextField.userInteractionEnabled = true
cell.recipientTextField.becomeFirstResponder()
isCcBccSelected = true
tableView.beginUpdates()
tableView.endUpdates()
}
}
}
}
setSelectedByText:function(eID,text) {
var ele=document.getElementById(eID);
for(var ii=0; ii<ele.length; ii++)
if(ele.options[ii].text==text) { //Found!
ele.options[ii].selected=true;
return true;
}
return false;
},
Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.
All transaction must contain four properties that commonly known as ACID properties. i.e ACID are the group of properties of any transaction.
I needed to get both USB and TCPIP working for ADB (don't ask), so I did the following (using directions others have posted from xda-developers)
Using adb shell
:
su
#Set the port number for adbd
setprop service.adb.tcp.port 5555
#Run the adbd daemon *again* instead of doing stop/start, so there
#are two instances of adbd running.
adbd &
#Set the port back to USB, so the next time ADB is started it's
#on USB again.
setprop service.adb.tcp.port -1
exit
You might want to do something like this (if you're using java 5 and more)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt())
{
tall[i++] = scanner.nextInt();
}
Via Julian Grenier from Reading Integers From A File In An Array
Static Memory Allocation:
Dynamic Memory Allocation:
On some servers and web hosts, it's possible to disable ModSecurity via .htaccess
, but be aware that you can only switch it on or off, you can't disable individual rules.
But a good practice that still keeps your site secure is to disable it only on specific URLs, rather than your entire site. You can specify which URLs to match via the regex in the <If>
statement below...
### DISABLE mod_security firewall
### Some rules are currently too strict and are blocking legitimate users
### We only disable it for URLs that contain the regex below
### The regex below should be placed between "m#" and "#"
### (this syntax is required when the string contains forward slashes)
<IfModule mod_security.c>
<If "%{REQUEST_URI} =~ m#/admin/#">
SecFilterEngine Off
SecFilterScanPOST Off
</If>
</IfModule>
I have this function...
var escapeURIparam = function(url) {
if (encodeURIComponent) url = encodeURIComponent(url);
else if (encodeURI) url = encodeURI(url);
else url = escape(url);
url = url.replace(/\+/g, '%2B'); // Force the replacement of "+"
return url;
};
After searching for this myself wanting several projects with shared dependencies to be DRYer, I’ve found:
require()
require()
bin
and man
paths to $PATH
npm link
(info) lets you use a local install as a source for globals? stick to the Node way and install locally
ref:
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
I would really recommend anyone entering this subject to read Addy Osmani's free book:
"Learning JavaScript Design Patterns".
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
This book helped me out immensely when I was starting into writing more maintainable JavaScript and I still use it as a reference. Have a look at his different module pattern implementations, he explains them really well.
Android has all the tools you need to parse json built-in. Example follows, no need for GSON or anything like that.
Get your JSON:
Assume you have a json string
String result = "{\"someKey\":\"someValue\"}";
Create a JSONObject:
JSONObject jObject = new JSONObject(result);
If your json string is an array, e.g.:
String result = "[{\"someKey\":\"someValue\"}]"
then you should use JSONArray
as demonstrated below and not JSONObject
To get a specific string
String aJsonString = jObject.getString("STRINGNAME");
To get a specific boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
To get a specific integer
int aJsonInteger = jObject.getInt("INTEGERNAME");
To get a specific long
long aJsonLong = jObject.getLong("LONGNAME");
To get a specific double
double aJsonDouble = jObject.getDouble("DOUBLENAME");
To get a specific JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
To get the items from the array
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:
readonly DateTime a = DateTime.Now;
I agree, if you have a const pre-defined array you might as well make it static. At that point you can use this interesting syntax:
//in header file
class a{
static const int SIZE;
static const char array[][10];
};
//in cpp file:
const int a::SIZE = 5;
const char array[SIZE][10] = {"hello", "cruel","world","goodbye", "!"};
however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.
You could try using the system stored procedure sp_help_job. This returns information on the job, its steps, schedules and servers. For example
EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'
SQL Books Online should contain lots of information about the records it returns.
For returning information on multiple jobs, you could try querying the following system tables which hold the various bits of information on the job
Their names are fairly self-explanatory (apart from SysJobServers which hold information on when the job last run and the outcome).
Again, information on the fields can be found at MSDN. For example, check out the page for SysJobs
exit
in the C language takes an integer representing an exit status.
Typically, an exit status of 0 is considered a success, or an intentional exit caused by the program's successful execution.
An exit status of 1 is considered a failure, and most commonly means that the program had to exit for some reason, and was not able to successfully complete everything in the normal program flow.
Here's a GNU Resource talking about Exit Status.
As @Als has stated, two constants should be used in place of 0 and 1.
EXIT_SUCCESS
is defined by the standard to be zero.
EXIT_FAILURE
is not restricted by the standard to be one, but many systems do implement it as one.
None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:
$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.
The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.
As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.
Should be .\SQLExpress
or localhost\SQLExpress
no $ sign at the end
See also here http://www.connectionstrings.com/sql-server-2008
The suggested solutions are incompatible with Seaborn 0.8.1
giving the following errors because the Seaborn interface has changed:
AttributeError: 'AxesSubplot' object has no attribute 'fig'
When trying to access the figure
AttributeError: 'AxesSubplot' object has no attribute 'savefig'
when trying to use the savefig directly as a function
The following calls allow you to access the figure (Seaborn 0.8.1 compatible):
swarm_plot = sns.swarmplot(...)
fig = swarm_plot.get_figure()
fig.savefig(...)
as seen previously in this answer.
UPDATE: I have recently used PairGrid object from seaborn to generate a plot similar to the one in this example. In this case, since GridPlot is not a plot object like, for example, sns.swarmplot, it has no get_figure() function. It is possible to directly access the matplotlib figure by
fig = myGridPlotObject.fig
Like previously suggested in other posts in this thread.
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.
But don't just take my word for it, Josh Bloch also says it's bad:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
Alternatively,
<style type="text/css">
#example {
display: block;
width: 30px;
height: 10px;
background: url(../images/example.png) no-repeat;
text-indent: -9999px;
}
</style>
<a href="http://www.example.com" id="example">See an example!</a>
More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.
This is fixed by setting the module
compiler option to es6
:
{
"compilerOptions": {
"module": "es6",
"target": "es5",
}
}
There is no way how to declare an unsigned long or int in Java 8 or Java 9. But some methods treat them as if they were unsigned, for example:
static long values = Long.parseUnsignedLong("123456789012345678");
but this is not declaration of the variable.
As per W3C spec,
The list properties ... do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker ...
But the idea with a span inside the list above should work fine!
Put the database password in a file, make it read-only to the user serving the files.
Unless you have some means of only allowing the php server process to access the database, this is pretty much all you can do.
I dont know if you solved this issue, but i had same issue, if the instance is local you must check the permission to access the file, but if you are accessing from your computer to a server (remote access) you have to specify the path in the server, so that means to include the file in a server directory, that solved my case
example:
BULK INSERT Table
FROM 'C:\bulk\usuarios_prueba.csv' -- This is server path not local
WITH
(
FIELDTERMINATOR =',',
ROWTERMINATOR ='\n'
);
There is a way to change the package name easily in Eclipse. Right click on your project, scroll down to Android Tools, and then click on Rename Application Package.
Overhead typically reffers to the amount of extra resources (memory, processor, time, etc.) that different programming algorithms take.
For example, the overhead of inserting into a balanced Binary Tree could be much larger than the same insert into a simple Linked List (the insert will take longer, use more processing power to balance the Tree, which results in a longer percieved operation time by the user).
jQuery('input[name="inputName"]:checked').val()
As it was mentioned above, the answer depends on your case. If you want to escape a string for a regular expression then you should use re.escape(). But if you want to escape a specific set of characters then use this lambda function:
>>> escape = lambda s, escapechar, specialchars: "".join(escapechar + c if c in specialchars or c == escapechar else c for c in s)
>>> s = raw_input()
I'm "stuck" :\
>>> print s
I'm "stuck" :\
>>> print escape(s, "\\", ['"'])
I'm \"stuck\" :\\
Use:
struct arg_struct *args = malloc(sizeof(struct arg_struct));
And pass this arguments like this:
pthread_create(&tr, NULL, print_the_arguments, (void *)args);
Don't forget free args! ;)
This is an addition to dmd733's answer. I fixed the bug with Day duration (well I hope I did, haven't been able to test every case).
I also quickly added a String property to the result that holds the general time passed (sorry for the bad nested ifs!!). For example if used for UI and indicating when something was updated (like a RSS feed). Kind of out of place but nice-to-have:
function getTimeDiffAndPrettyText(oDatePublished) {
var oResult = {};
var oToday = new Date();
var nDiff = oToday.getTime() - oDatePublished.getTime();
// Get diff in days
oResult.days = Math.floor(nDiff / 1000 / 60 / 60 / 24);
nDiff -= oResult.days * 1000 * 60 * 60 * 24;
// Get diff in hours
oResult.hours = Math.floor(nDiff / 1000 / 60 / 60);
nDiff -= oResult.hours * 1000 * 60 * 60;
// Get diff in minutes
oResult.minutes = Math.floor(nDiff / 1000 / 60);
nDiff -= oResult.minutes * 1000 * 60;
// Get diff in seconds
oResult.seconds = Math.floor(nDiff / 1000);
// Render the diffs into friendly duration string
// Days
var sDays = '00';
if (oResult.days > 0) {
sDays = String(oResult.days);
}
if (sDays.length === 1) {
sDays = '0' + sDays;
}
// Format Hours
var sHour = '00';
if (oResult.hours > 0) {
sHour = String(oResult.hours);
}
if (sHour.length === 1) {
sHour = '0' + sHour;
}
// Format Minutes
var sMins = '00';
if (oResult.minutes > 0) {
sMins = String(oResult.minutes);
}
if (sMins.length === 1) {
sMins = '0' + sMins;
}
// Format Seconds
var sSecs = '00';
if (oResult.seconds > 0) {
sSecs = String(oResult.seconds);
}
if (sSecs.length === 1) {
sSecs = '0' + sSecs;
}
// Set Duration
var sDuration = sDays + ':' + sHour + ':' + sMins + ':' + sSecs;
oResult.duration = sDuration;
// Set friendly text for printing
if(oResult.days === 0) {
if(oResult.hours === 0) {
if(oResult.minutes === 0) {
var sSecHolder = oResult.seconds > 1 ? 'Seconds' : 'Second';
oResult.friendlyNiceText = oResult.seconds + ' ' + sSecHolder + ' ago';
} else {
var sMinutesHolder = oResult.minutes > 1 ? 'Minutes' : 'Minute';
oResult.friendlyNiceText = oResult.minutes + ' ' + sMinutesHolder + ' ago';
}
} else {
var sHourHolder = oResult.hours > 1 ? 'Hours' : 'Hour';
oResult.friendlyNiceText = oResult.hours + ' ' + sHourHolder + ' ago';
}
} else {
var sDayHolder = oResult.days > 1 ? 'Days' : 'Day';
oResult.friendlyNiceText = oResult.days + ' ' + sDayHolder + ' ago';
}
return oResult;
}
I had this problem when I was using an undefined variable inside the with open(...) as f:
.
I removed (or I defined outside) the undefined variable and the problem disappeared.
The following solved my problem of converting string into date
package main
import (
"fmt"
"time"
)
func main() {
value := "Thu, 05/19/11, 10:47PM"
// Writing down the way the standard time would look like formatted our way
layout := "Mon, 01/02/06, 03:04PM"
t, _ := time.Parse(layout, value)
fmt.Println(t)
}
// => "Thu May 19 22:47:00 +0000 2011"
I like the explanation From EdX (Microsoft: DEV210x Introduction to C++) for a similar problem:
"The enum represents the literal values of days as integers. Referring to the numeric types table, you see that an int takes 4 bytes of memory. 7 days x 4 bytes each would require 28 bytes of memory if the entire enum were stored but the compiler only uses a single element of the enum, therefore the size in memory is actually 4 bytes."
I believe that you can omit updating the "non-desired" columns by adjusting the other answers as follows:
update table set
columnx = (case when condition1 then 25 end),
columny = (case when condition2 then 25 end)`
As I understand it, this will update only when the condition is met.
After reading all the comments, this is the most efficient:
Update table set ColumnX = 25 where Condition1
Update table set ColumnY = 25 where Condition1`
Sample Table:
CREATE TABLE [dbo].[tblTest](
[ColX] [int] NULL,
[ColY] [int] NULL,
[ColConditional] [bit] NULL,
[id] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
Sample Data:
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 0)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1)
Insert into tblTest (ColX, ColY, ColConditional) values (null, null, 1)
Insert into tblTest (ColX, ColY, ColConditional) values (1, null, null)
Insert into tblTest (ColX, ColY, ColConditional) values (2, null, null)
Insert into tblTest (ColX, ColY, ColConditional) values (null, 1, null)
Insert into tblTest (ColX, ColY, ColConditional) values (null, 2, null)
Now I assume you can write a conditional that handles nulls. For my example, I am assuming you have written such a conditional that evaluates to True, False or Null. If you need help with this, let me know and I will do my best.
Now running these two lines of code does infact change X to 25 if and only if ColConditional is True(1) and Y to 25 if and only if ColConditional is False(0)
Update tblTest set ColX = 25 where ColConditional = 1
Update tblTest set ColY = 25 where ColConditional = 0
P.S. The null case was never mentioned in the original question or any updates to the question, but as you can see, this very simple answer handles them anyway.
For those looking for the Firebase Firestore equivalent. It's
firebase.firestore.FieldValue.serverTimestamp()
e.g.
firebase.firestore().collection("cities").add({
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
name: "Tokyo",
country: "Japan"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
Templates. I think that is Smarty syntax.
To make this simple: PyPy provides the speed that's lacked by CPython but sacrifices its compatibility. Most people, however, choose Python for its flexibility and its "battery-included" feature (high compatibility), not for its speed (it's still preferred though).
I found a tricky solution... which works only in a RelativeLayout. We only need to put a View above a ListView and set clickable 'true' on View and false for the ListView
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview
android:clickable="false" />
<View
android:layout_width="match_parent"
android:background="@drawable/gradient_white"
android:layout_height="match_parent"
android:clickable="true"
android:layout_centerHorizontal="true"
android:layout_alignTop="@+id/listview" />
Change servername,username, password,dbname,path of your file, tablename and the field which is in your database you want to insert
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "bd_dashboard";
//For create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$query = "LOAD DATA LOCAL INFILE
'C:/Users/lenovo/Desktop/my_data.csv'
INTO TABLE test_tab
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(name,mob)";
if (!$result = mysqli_query($conn, $query)){
echo '<script>alert("Oops... Some Error occured.");</script>';
exit();
//exit(mysqli_error());
}else{
echo '<script>alert("Data Inserted Successfully.");</script>'
}
?>
1.) Storage of database passwords Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.
2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.
The query should then look like this:
select hashedPassword from users where username=?
Then compare the password to the input.
Further questions?
You could:
SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1
INTO res;
This happens to work, because your query has an aggregate function and consequently always returns a row, even if nothing is found in the underlying table.
Plain queries without aggregate would return no row in such a case. COALESCE
would never be called and couldn't save you. While dealing with a single column we can wrap the whole query instead:
SELECT COALESCE( (SELECT columnA FROM my_table WHERE ID = 1), 0)
INTO res;
Works for your original query as well:
SELECT COALESCE( (SELECT SUM(columnA) FROM my_table WHERE columnB = 1), 0)
INTO res;
More about COALESCE()
in the manual.
More about aggregate functions in the manual.
More alternatives in this later post:
Googling gives me this:
Command A & Command B
Execute Command A, then execute Command B (no evaluation of anything)
Command A | Command B
Execute Command A, and redirect all its output into the input of Command B
Command A && Command B
Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B
Command A || Command B
Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B
int [] newArray = new int[old1.length+old2.length];
System.arraycopy( old1, 0, newArray, 0, old1.length);
System.arraycopy( old2, 0, newArray, old1.length, old2.length );
Don't use element-by-element copying, it's very slow compared to System.arraycopy()
Excel shows 24:03 as 3 minutes when you format it as time, because 24:03 is the same as 12:03 AM (in military time).
Instead of trying to format as Time, use the General Format and the following formula:
=number of minutes + (number of seconds / 60)
Ex: for 24 minutes and 3 seconds:
=24+3/60
This will give you a value of 24.05.
Do this for each time period. Let's say you enter this formula in cells A1
and A2
. Then, to get the total sum of elapsed time, use this formula in cell A3
:
=INT(A1+A2)+MOD(A1+A2,1)
If you put =24+3/60
into each cell, you will have a value of 48.1 in cell A3
.
Now you need to convert this back to minutes and seconds. Use the following formula in cell A4
:
=MOD(A3,1)*60
This takes the decimal portion and multiples it by 60. Remember, we divided by 60 in the beginning, so to convert it back to seconds we need to multiply.
You could have also done this separately, i.e. in cell A3 use this formula:
=INT(A1+A2)
and this formula in cell A4
:
=MOD(A1+A2,1)*60
Here's a screenshot showing the final formulas:
Generally this is due to the DOM being updated and you trying to access an updated/new element -- but the DOM's refreshed so it's an invalid reference you have..
Get around this by first using an explicit wait on the element to ensure the update is complete, then grab a fresh reference to the element again.
Here's some psuedo code to illustrate (Adapted from some C# code I use for EXACTLY this issue):
WebDriverWait wait = new WebDriverWait(browser, TimeSpan.FromSeconds(10));
IWebElement aRow = browser.FindElement(By.XPath(SOME XPATH HERE);
IWebElement editLink = aRow.FindElement(By.LinkText("Edit"));
//this Click causes an AJAX call
editLink.Click();
//must first wait for the call to complete
wait.Until(ExpectedConditions.ElementExists(By.XPath(SOME XPATH HERE));
//you've lost the reference to the row; you must grab it again.
aRow = browser.FindElement(By.XPath(SOME XPATH HERE);
//now proceed with asserts or other actions.
Hope this helps!
<?php
if (isset($_POST['birthdate'])) {
$timestamp = strtotime($_POST['birthdate']);
$date=date('d',$timestamp);
$month=date('m',$timestamp);
$year=date('Y',$timestamp);
}
?>
Just had a simple variant problem... Convert files of typed .flv to .mp3 (yawn).
for file in read `find . *.flv`; do ffmpeg -i ${file} -acodec copy ${file}.mp3;done
recursively find all the Macintosh user flash files and turn them into audio (copy, no transcode) ... it's like the while above, noting that read instead of just 'for file in ' will escape.
The line height of the <br>
can be different from the line height of the rest of the text inside a <p>
. You can control the line height of your <br>
tags independently of the rest of the text by enclosing two of them in a <span>
that is styled. Use the line-height
css property, as others have suggested.
<p class="normalLineHeight">
Lots of text here which will display on several lines with normal line height if you put it in a narrow container...
<span class="customLineHeight"><br><br></span>
After a custom break, this text will again display on several lines with normal line height...
</p>
Ok maybe this one should solve your problem. Note that each time you make a change you call the change() method that releases the wait.
Integer any = new Integer(0);
public synchronized boolean waitTillChange() {
any.wait();
return true;
}
public synchronized void change() {
any.notify();
}
This commonly happened use case for any developer.
It is better to have it as function in your local system. (So better to keep this script in one of the shell profile like ksh/zsh or bash profile based on the user preference)
function killport {
kill -9 `lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'`
}
Usage:
killport port_number
Example:
killport 8080
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
How about something like
git log --pretty=oneline master > 1
git log --pretty=oneline branch_A > 2
git rev-parse `diff 1 2 | tail -1 | cut -c 3-42`^
assuming your using click events, just unbind that one.
example
if (current = 1){
$('li:eq(2)').unbind("click");
}
EDIT:
Are you currently binding a click event to your list somewhere? Based on your comment above, I'm wondering if this is really what you're doing? How are you enabling the click? Is it just an anchor(<a>
tag) ? A little more explicit information will help us answer your question.
UPDATE:
Did some playing around with the :eq() operator. http://jsfiddle.net/ehudokai/VRGfS/5/
As I should have expected it is a 0 based index operator. So if you want to turn of the second element in your selection, where your selection is
$("#navigation a")
you would simply add :eq(1) (the second index) and then .unbind("click") So:
if(current == 1){
$("#navigation a:eq(1)").unbind("click");
}
Ought to do the trick.
Hope this helps!
the possibility of two main(String[] args) methods within the same scope create confusion for the JVM. It fails to use them as overloaded methods. So the signatures in terms of parameters) must be different.
Using Bootstrap's built in .center-block
class, which sets margin left and right to auto
:
<iframe class="center-block" width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
Or using the built in .text-center
class, which sets text-align: center
:
<div class="text-center">
<iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div>
I would also note there are two ways to get the number of ms in the time point. I'm not sure which one is better, I've benchmarked them and they both have the same performance, so I guess it's a matter of preference. Perhaps Howard could chime in:
auto now = system_clock::now();
//Cast the time point to ms, then get its duration, then get the duration's count.
auto ms = time_point_cast<milliseconds>(now).time_since_epoch().count();
//Get the time point's duration, then cast to ms, then get its count.
auto ms = duration_cast<milliseconds>(tpBid.time_since_epoch()).count();
The first one reads more clearly in my mind going from left to right.
The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.
Also you might want to log in via browser and get the command with all headers including cookies:
Open the Network tab of Developer Tools, log in, navigate to the needed page, use "Copy as cURL".
Keyword float
:
<h1 style="text-align:left;float:left;">Title</h1>
<h2 style="text-align:right;float:right;">Context</h2>
<hr style="clear:both;"/>
Maybe it's too late, but here it goes.
We can use the attribute EnumMember to manage Enum values.
public enum EUnitOfMeasure
{
[EnumMember(Value = "KM")]
Kilometer,
[EnumMember(Value = "MI")]
Miles
}
This way the result value for EUnitOfMeasure will be KM or MI. This also can be seen in Andrew Whitaker answer.
I found theDuncs answer very useful and below you can find my own (refactored) version:
- (void)viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShow:(NSNotification *)notification {
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
float newVerticalPosition = -keyboardSize.height;
[self moveFrameToVerticalPosition:newVerticalPosition forDuration:0.3f];
}
- (void)keyboardWillHide:(NSNotification *)notification {
[self moveFrameToVerticalPosition:0.0f forDuration:0.3f];
}
- (void)moveFrameToVerticalPosition:(float)position forDuration:(float)duration {
CGRect frame = self.view.frame;
frame.origin.y = position;
[UIView animateWithDuration:duration animations:^{
self.view.frame = frame;
}];
}
<input type="button" id="btnTexWrapped" style="background:
url('http://i0006.photobucket.com/albums/0006/findstuff22/Backgrounds/bokeh2backgrounds.jpg');background-size:30px;width:50px;height:3em;" />
Change input style elements as you want to get the button you need.
I hope it was helpful.
In Koltin
Add kotlin extension in your build.gradle.
apply plugin: 'kotlin-android-extensions'
android {
androidExtensions {
experimental = true
}
}
Then create your data class like this.
@Parcelize
data class Sample(val id: Int, val name: String) : Parcelable
Pass Object with Intent
val sample = Sample(1,"naveen")
val intent = Intent(context, YourActivity::class.java)
intent.putExtra("id", sample)
startActivity(intent)
Get object with intent
val sample = intent.getParcelableExtra("id")
You can use Google Guava Table
// convert file to a base64 url
const readURL = file => {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = e => res(e.target.result);
reader.onerror = e => rej(e);
reader.readAsDataURL(file);
});
};
// for demo
const fileInput = document.createElement('input');
fileInput.type = 'file';
const img = document.createElement('img');
img.attributeStyleMap.set('max-width', '320px');
document.body.appendChild(fileInput);
document.body.appendChild(img);
const preview = async event => {
const file = event.target.files[0];
const url = await readURL(file);
img.src = url;
};
fileInput.addEventListener('change', preview);
_x000D_
I've used these shortcuts in the past (note: separate key strokes i.e. tap z, let go, tap the subsequent key):
z enter --> moves current line to top of screen
z . --> moves current line to center of screen
z - --> moves current line to bottom
If it's not obvious:
enter means the Return or Enter key.
. means the DOT or "full stop" key (.
).
- means the HYPHEN key (-
)
For what it's worth, z. avoids the danger of saving and closing Vi by accidentally typing ZZ if the caps-lock is on.
Have you looked at angular-ui bootstrap? There's a Dialog (ui.bootstrap.dialog) directive that works quite well. You can close the dialog during the call back the angular way (per the example):
$scope.close = function(result){
dialog.close(result);
};
Update:
The directive has since been renamed Modal.
Public Function LastData(rCol As Range) As Range
Set LastData = rCol.Find("*", rCol.Cells(1), , , , xlPrevious)
End Function
Usage: ?lastdata(activecell.EntireColumn).Address
#include <math.h>
double round(double x);
float roundf(float x);
Don't forget to link with -lm. See also ceil(), floor() and trunc().
Daniel A. White Solution works great for classes.
I've got a situation where I had to find input fields like donee_1_card where 1 is an index.
My solution has been
$("input[name^='donee']" && "input[name*='card']")
Though I am not sure how optimal it is.
Stash is just a convenience method. Since branches are so cheap and easy to manage in git, I personally almost always prefer creating a new temporary branch than stashing, but it's a matter of taste mostly.
The one place I do like stashing is if I discover I forgot something in my last commit and have already started working on the next one in the same branch:
# Assume the latest commit was already done
# start working on the next patch, and discovered I was missing something
# stash away the current mess I made
git stash save
# some changes in the working dir
# and now add them to the last commit:
git add -u
git commit --amend
# back to work!
git stash pop
Method 1:
If the method DoSomethingBeta was static you need only call:
Beta.DoSomethingBeta();
Method 2:
If Alpha extends from Beta you could call DoSomethingBeta() directly.
public class Alpha extends Beta{
public void DoSomethingAlpha() {
DoSomethingBeta(); //?
}
}
Method 3:
Alternatively you need to have access to an instance of Beta to call the methods from it.
public class Alpha {
public void DoSomethingAlpha() {
Beta cbeta = new Beta();
cbeta.DoSomethingBeta(); //?
}
}
Incidentally is this homework?
This article explains that your sequence might be out of sync and that you have to manually bring it back in sync.
An excerpt from the article in case the URL changes:
If you get this message when trying to insert data into a PostgreSQL database:
ERROR: duplicate key violates unique constraint
That likely means that the primary key sequence in the table you're working with has somehow become out of sync, likely because of a mass import process (or something along those lines). Call it a "bug by design", but it seems that you have to manually reset the a primary key index after restoring from a dump file. At any rate, to see if your values are out of sync, run these two commands:
SELECT MAX(the_primary_key) FROM the_table; SELECT nextval('the_primary_key_sequence');
If the first value is higher than the second value, your sequence is out of sync. Back up your PG database (just in case), then run thisL
SELECT setval('the_primary_key_sequence', (SELECT MAX(the_primary_key) FROM the_table)+1);
That will set the sequence to the next available value that's higher than any existing primary key in the sequence.
int myArray[10][10][10];
should be
int myArray[10][10][10][10];
No, Java doesn't have something like C#'s ref
and out
keywords for passing by reference.
You can only pass by value in Java. Even references are passed by value. See Jon Skeet's page about parameter passing in Java for more details.
To do something similar to ref
or out
you would have to wrap your parameters inside another object and pass that object reference in as a parameter.
Be aware that, as written, Peter's solution will "accept" 0000
. If you want to validate numbers between 1000
and 999999
, then that is another problem :-)
^[1-9][0-9]{3,5}$
for example will block inserting 0
at the beginning of the string.
If you want to accept 0 padding, but only up to a lengh of 6, so that 001000
is valid, then it becomes more complex. If we use look-ahead then we can write something like
^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$
This first checks if the string is long 4-6 (?=[0-9]{4,6}$)
, then skips the 0s 0*
and search for a non-zero [1-9]
followed by at least 3 digits [0-9]{3,}
.
Here are some I can think about :
bindParam
, you can only pass variables ; not valuesbindValue
, you can pass both (values, obviously, and variables)bindParam
works only with variables because it allows parameters to be given as input/output, by "reference" (and a value is not a valid "reference" in PHP) : it is useful with drivers that (quoting the manual) : support the invocation of stored procedures that return data as output parameters, and some also as input/output parameters that both send in data and are updated to receive it.
With some DB engines, stored procedures can have parameters that can be used for both input (giving a value from PHP to the procedure) and ouput (returning a value from the stored proc to PHP) ; to bind those parameters, you've got to use bindParam, and not bindValue.
In case you are indeed using the SSH URL, but still are asked for username and password when git pushing:
git remote set-url origin [email protected]:<Username>/<Project>.git
You should try troubleshooting with:
ssh -vT [email protected]
Below is a piece of sample output:
...
debug1: Trying private key: /c/Users/Yuci/.ssh/id_rsa
debug1: Trying private key: /c/Users/Yuci/.ssh/id_dsa
debug1: Trying private key: /c/Users/Yuci/.ssh/id_ecdsa
debug1: Trying private key: /c/Users/Yuci/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).
I actually have already added the public key to GitHub before, and I also have the private key locally. However, my private key is of a different name called /c/Users/Yuci/.ssh/github_rsa
.
According to the sample output, Git is trying /c/Users/Yuci/.ssh/id_rsa
, which I don't have. Therefore, I could simply copy github_rsa
to id_rsa
in the same directory.
cp /c/Users/Yuci/.ssh/github_rsa /c/Users/Yuci/.ssh/id_rsa
Now when I run ssh -vT [email protected]
again, I have:
...
debug1: Trying private key: /c/Users/Yuci/.ssh/id_rsa
debug1: Authentication succeeded (publickey).
...
Hi <my username>! You've successfully authenticated, but GitHub does not provide shell access.
...
And now I can push to GitHub without being asked for username and password :-)
Kotlin example:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_signin)
packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES).apply {
findViewById<TextView>(R.id.text_version_name).text = versionName
findViewById<TextView>(R.id.text_version_code).text =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) "$longVersionCode" else "$versionCode"
}
packageManager.getApplicationInfo(packageName, 0).apply{
findViewById<TextView>(R.id.text_build_date).text =
SimpleDateFormat("yy-MM-dd hh:mm").format(java.io.File(sourceDir).lastModified())
}
}
From MSDN:
To change security authentication mode:
In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties.
On the Security page, under Server authentication, select the new server authentication mode, and then click OK.
In the SQL Server Management Studio dialog box, click OK to acknowledge the requirement to restart SQL Server.
In Object Explorer, right-click your server, and then click Restart. If SQL Server Agent is running, it must also be restarted.
To enable the SA login:
In Object Explorer, expand Security, expand Logins, right-click SA, and then click Properties.
On the General page, you might have to create and confirm a password for the login.
On the Status page, in the Login section, click Enabled, and then click OK.
you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)
In order to jump out of a loop, you need to use the break statement.
n=L[0][0]
m=len(A)
for i in range(m):
for j in range(m):
if L[i][j]!=n:
break;
Here you have the official Python manual with the explanation about break and continue, and other flow control statements:
http://docs.python.org/tutorial/controlflow.html
EDITED: As a commenter pointed out, this does only end the inner loop. If you need to terminate both loops, there is no "easy" way (others have given you a few solutions). One possiblity would be to raise an exception:
def f(L, A):
try:
n=L[0][0]
m=len(A)
for i in range(m):
for j in range(m):
if L[i][j]!=n:
raise RuntimeError( "Not equal" )
return True
except:
return False
You need to grant SELECT permissions to the MySQL user who is connecting to MySQL
same question as here Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'
see answers of the link ;)
You might have done something like this:
>>> tuple = 45, 34 # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l) # Will try to invoke the variable `tuple` rather than tuple type.
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
tuple(l)
TypeError: 'tuple' object is not callable
>>>
>>> del tuple # You can delete the object tuple created earlier to make it work
>>> tuple(l)
(4, 5, 6)
Here's the problem... Since you have used a tuple
variable to hold a tuple (45, 34)
earlier... So, now tuple
is an object
of type tuple
now...
It is no more a type
and hence, it is no more Callable
.
Never
use any built-in types as your variable name... You do have any other name to use. Use any arbitrary name for your variable instead...
var formValues = {
firstName: $('#firstName').val(),
lastName: $('#lastName').val(),
phone: $('#phoneNumber').val(),
address: $('#address').val()
};
Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.
To expand on the answer given by Chris
if you want to store the date in a variable in a specific format, this is the shortest and most effective way as far as I know
>>> from datetime import date, timedelta
>>> yesterday = (date.today() - timedelta(days=1)).strftime('%m%d%y')
>>> yesterday
'020817'
If you want it as an integer (which can be useful)
>>> yesterday = int((date.today() - timedelta(days=1)).strftime('%m%d%y'))
>>> yesterday
20817
the val
function called from the select
will return an array if its a multiple. $('select#my_multiselect').val()
will return an array of the values for the selected options - you dont need to loop through and get them yourself.
I think this original question indirectly points to a general recommendation that run-time null-pointer check is still needed, even though @NonNull is used. Refer to the following link:
In the above blog, it is recommended that:
Optional Type Annotations are not a substitute for runtime validation Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification. Your code should still perform runtime validation.
Look at the package DBMS_Redefinition. It will rebuild the table with the new ordering. It can be done with the table online.
As Phil Brown noted, think carefully before doing this. However there is overhead in scanning the row for columns and moving data on update. Column ordering rules I use (in no particular order):
These rules conflict and have not all been tested for performance on the latest release. Most have been tested in practice, but I didn't document the results. Placement options target one of three conflicting goals: easy to understand column placement; fast data retrieval; and minimal data movement on updates.
One more alternative is json-simple which can be found in Maven Central:
(JSONObject)JSONValue.parse(someString); //JSONObject is actually a Map.
The artifact is 24kbytes, doesn't have other runtime dependencies.
Check your php.ini, I'm using Apache2.2 + php 5.3. and I had the same problem and after modify the php.ini in order to set the libraries directory of PHP, it worked correctly. The problem is the default extension_dir
configuration value.
The default (and WRONG) value for my work enviroment is
; extension_dir="ext"
without any full path and commented with a semicolon.
There are two solution that worked fine for me.
1.- Including this line at php.ini file
extension_dir="X:/[PathToYourPHPDirectory]/ext
Where X: is your drive letter instalation (normally C: or D: )
2.- You can try to simply uncomment, deleting semicolon. Include the next line at php.ini file
extension_dir="ext"
Both ways worked fine for me but choose yours. Don't forget restart Apache before try again.
I hope this help you.
You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.
Also, I don't think you can use NOW()
as default value in OrderDate. Try to use the following:
OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.
The answer to it is a interval parameter which fixes things up
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt
np.random.seed(1)
N = 100
y = np.random.rand(N)
now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()
Append .done()
to your ajax request.
$.ajax({
url: "test.html",
context: document.body
}).done(function() { //use this
alert("DONE!");
});
See the JQuery Doc for .done()
After reading all answers and some more research I get a few things.
Case statements are only 'labels'
In C, according to the specification,
§6.8.1 Labeled Statements:
labeled-statement:
identifier : statement
case constant-expression : statement
default : statement
In C there isn't any clause that allows for a "labeled declaration". It's just not part of the language.
So
case 1: int x=10;
printf(" x is %d",x);
break;
This will not compile, see http://codepad.org/YiyLQTYw. GCC is giving an error:
label can only be a part of statement and declaration is not a statement
Even
case 1: int x;
x=10;
printf(" x is %d",x);
break;
this is also not compiling, see http://codepad.org/BXnRD3bu. Here I am also getting the same error.
In C++, according to the specification,
labeled-declaration is allowed but labeled -initialization is not allowed.
See http://codepad.org/ZmQ0IyDG.
Solution to such condition is two
Either use new scope using {}
case 1:
{
int x=10;
printf(" x is %d", x);
}
break;
Or use dummy statement with label
case 1: ;
int x=10;
printf(" x is %d",x);
break;
Declare the variable before switch() and initialize it with different values in case statement if it fulfills your requirement
main()
{
int x; // Declare before
switch(a)
{
case 1: x=10;
break;
case 2: x=20;
break;
}
}
Some more things with switch statement
Never write any statements in the switch which are not part of any label, because they will never executed:
switch(a)
{
printf("This will never print"); // This will never executed
case 1:
printf(" 1");
break;
default:
break;
}
it's much easier than you think to write your own, just use an interface for JsonElementInterface
with a method string toJson()
, and an abstract class AbstractJsonElement
implementing that interface,
then all you have to do is have a class for JSONProperty
that implements the interface, and JSONValue
(any token), JSONArray
([...]), and JSONObject
({...}) that extend the abstract class
JSONObject
has a list of JSONProperty
's
JSONArray
has a list of AbstractJsonElement
's
your add function in each should take a vararg list of that type, and return this
now if you don't like something you can just tweak it
the benifit of the inteface and the abstract class is that JSONArray
can't accept properties, but JSONProperty
can accept objects or arrays
The Prototype library includes a Hashtable object, with a ".toQueryString()" method, which allows you to easily turn a JavaScript object/structure into a query-string style string. Since the post requires the "body" of the request to be a query-string formatted string, this allows your Ajax request to work properly as a post. Here's an example using Prototype:
$req = new Ajax.Request("http://foo.com/bar.php",{
method: 'post',
parameters: $H({
name: 'Diodeus',
question: 'JavaScript posts a request like a form request',
...
}).toQueryString();
};
While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.
Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">
And add to your javascript-file (or section within the page):
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.
Use -C
option of tar:
tar zxvf <yourfile>.tar.gz -C /usr/src/
and then, the content of the tar should be in:
/usr/src/<yourfile>
if you are on linux, edit the /etc/php/php.ini
(or you will have to create a new extension import file at /etc/php5/cli/conf.d) file so that you add the imap shared object file and then, restart the apache server. Uncomment
;extension=imap.so
so that it becomes like this:
extension=imap.so
Then, restart the apache by
# /etc/rc.d/httpd restart
I have the same issue, and solved by change the '+' to a exact number, like compile "com.android.support:appcompat-v7:21.0.+" to compile "com.android.support:appcompat-v7:21.0.0".
This works for me. :)
LL(1) grammar is Context free unambiguous grammar which can be parsed by LL(1) parsers.
In LL(1)
For Checking grammar is LL(1) you can draw predictive parsing table. And if you find any multiple entries in table then you can say grammar is not LL(1).
Their is also short cut to check if the grammar is LL(1) or not . Shortcut Technique
My answer to this is the same as in an answer to your earlier question. For a probability density function, the integral over the entire space is 1. Dividing by the sum will not give you the correct density. To get the right density, you must divide by the area. To illustrate my point, try the following example.
[f, x] = hist(randn(10000, 1), 50); % Create histogram from a normal distribution.
g = 1 / sqrt(2 * pi) * exp(-0.5 * x .^ 2); % pdf of the normal distribution
% METHOD 1: DIVIDE BY SUM
figure(1)
bar(x, f / sum(f)); hold on
plot(x, g, 'r'); hold off
% METHOD 2: DIVIDE BY AREA
figure(2)
bar(x, f / trapz(x, f)); hold on
plot(x, g, 'r'); hold off
You can see for yourself which method agrees with the correct answer (red curve).
Another method (more straightforward than method 2) to normalize the histogram is to divide by sum(f * dx)
which expresses the integral of the probability density function, i.e.
% METHOD 3: DIVIDE BY AREA USING sum()
figure(3)
dx = diff(x(1:2))
bar(x, f / sum(f * dx)); hold on
plot(x, g, 'r'); hold off
From this link, we can understand IF THEN ELSE
in T-SQL:
IF EXISTS(SELECT *
FROM Northwind.dbo.Customers
WHERE CustomerId = 'ALFKI')
PRINT 'Need to update Customer Record ALFKI'
ELSE
PRINT 'Need to add Customer Record ALFKI'
IF EXISTS(SELECT *
FROM Northwind.dbo.Customers
WHERE CustomerId = 'LARSE')
PRINT 'Need to update Customer Record LARSE'
ELSE
PRINT 'Need to add Customer Record LARSE'
Isn't this good enough for T-SQL?
You can do this in many way.
- Using
display: flex
#block_container {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div id="block_container">_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</div>
_x000D_
- Using
display: inline-block
#block_container {_x000D_
text-align: center;_x000D_
}_x000D_
#block_container > div {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<div id="block_container">_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</div>
_x000D_
- using
table
<div>_x000D_
<table align="center">_x000D_
<tr>_x000D_
<td>_x000D_
<div id="bloc1">Copyright © All Rights Reserved.</div>_x000D_
</td>_x000D_
<td>_x000D_
<div id="bloc2"><img src="..."></div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
In my case, which none of the answers above stated. If your device is using the miniUsb connector, make sure you are using a cable that is not charge-only. I became accustom to using developing with a newer Usb-C device and could not fathom a charge-only cable got mixed with my pack especially since there is no visible way to tell the difference.
Before you uninstall and go through a nightmare of driver reinstall and android menu options. Try a different cable first.
I believe that you need to use CharSequence. You can find an example here.
It depends which version of C# you're using, from version 3.0 onwards you can use...
List<string> nameslist = new List<string> { "one", "two", "three" };
For python2, It's better to use e.message
to get the exception message, this will avoid possible UnicodeDecodeError
. But yes e.message
will be empty for some kind of exceptions like OSError
, in which case we can add a exc_info=True
to our logging function to not miss the error.
For python3, I think it's safe to use str(e)
.
Try this:
.slideContainer {_x000D_
overflow-x: scroll;_x000D_
white-space: nowrap;_x000D_
}_x000D_
.slide {_x000D_
display: inline-block;_x000D_
width: 600px;_x000D_
white-space: normal;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
<span class="slide">Some content</span>_x000D_
<span class="slide">More content. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>_x000D_
<span class="slide">Even more content!</span>_x000D_
</div>
_x000D_
Note that you can omit .slideContainer { overflow-x: scroll; }
(which browsers may or may not support when you read this), and you'll get a scrollbar on the window instead of on this container.
The key here is display: inline-block
. This has decent cross-browser support nowadays, but as usual, it's worth testing in all target browsers to be sure.
If this needs to work in IE 7 or lower you need to remember that getElementsByClassName does not exist in all browsers. Because of this you can create your own getElementsByClassName or you can try this.
var fooDiv = document.getElementById("foo");
for (var i = 0, childNode; i <= fooDiv.childNodes.length; i ++) {
childNode = fooDiv.childNodes[i];
if (/bar/.test(childNode.className)) {
childNode.innerHTML = "Goodbye world!";
}
}
http://joda-time.sourceforge.net/quickstart.html
Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:
* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class
I will give an example of what is Promise and how its value could be set at any time, in opposite to Future, which value is only readable.
Suppose you have a mom and you ask her for money.
// Now , you trick your mom into creating you a promise of eventual
// donation, she gives you that promise object, but she is not really
// in rush to fulfill it yet:
Supplier<Integer> momsPurse = ()-> {
try {
Thread.sleep(1000);//mom is busy
} catch (InterruptedException e) {
;
}
return 100;
};
ExecutorService ex = Executors.newFixedThreadPool(10);
CompletableFuture<Integer> promise =
CompletableFuture.supplyAsync(momsPurse, ex);
// You are happy, you run to thank you your mom:
promise.thenAccept(u->System.out.println("Thank you mom for $" + u ));
// But your father interferes and generally aborts mom's plans and
// completes the promise (sets its value!) with far lesser contribution,
// as fathers do, very resolutely, while mom is slowly opening her purse
// (remember the Thread.sleep(...)) :
promise.complete(10);
Output of that is:
Thank you mom for $10
Mom's promise was created , but waited for some "completion" event.
CompletableFuture<Integer> promise...
You created such event, accepting her promise and announcing your plans to thank your mom:
promise.thenAccept...
At this moment mom started open her purse...but very slow...
and father interfered much faster and completed the promise instead of your mom:
promise.complete(10);
Have you noticed an executor that I wrote explicitly?
Interestingly, if you use a default implicit executor instead (commonPool) and father is not at home, but only mom with her "slow purse", then her promise will only complete, if the program lives longer than mom needs to get money from the purse.
The default executor acts kind of like a "daemon" and does not wait for all promises to be fulfilled. I have not found a good description of this fact...
If you just want to sniff if a Source exists on the local machine but don't have ability to get authorization to do this, you can finger it through the following example (VB).
This bypasses the security error. You could similarly modify this function to return the LogName for the Source.
Public Shared Function eventLogSourceExists(sSource as String) as Boolean
Try
EventLog.LogNameFromSourceName(sSource, ".")
Return True
Catch
Return False
End Try
End Function
For folks like me looking at the accepted answer, and not understanding why it's not working, you need to add quotes around your sub directory, in the green checked example,
x_file = open(os.path.join(direct, "5_1.txt"), "r")
should actually be
x_file = open(os.path.join('direct', "5_1.txt"), "r")
How about this?
CASE WHEN ProductAlternateKey is NOT NULL THEN
CONVERT(NVARCHAR(25), LTRIM(RTRIM(ProductAlternateKey)))
FROM DimProducts
where ProductAlternateKey like '46783815%'
Including all referenced DLL files from your projectreferences in the Website project is not always a good idea, especially when you're using dependency injection: your web project just want to add a reference to the interface DLL file/project, not any concrete implementation DLL file.
Because if you add a reference directly to an implementation DLL file/project, you can't prevent your developer from calling a "new" on concrete classes of the implementation DLL file/project instead of via the interface. It's also you've stated a "hardcode" in your website to use the implementation.
I know you have already accepted another answer, but I think the broader issue needs to addressed - programming style that is suitable to the current language.
Yes, 'initialization' isn't needed in Python, but what you are doing isn't initialization. It is just an incomplete and erroneous imitation of initialization as practiced in other languages. The important thing about initialization in static typed languages is that you specify the nature of the variables.
In Python, as in other languages, you do need to give variables values before you use them. But giving them values at the start of the function isn't important, and even wrong if the values you give have nothing to do with values they receive later. That isn't 'initialization', it's 'reuse'.
I'll make some notes and corrections to your code:
def main():
# doc to define the function
# proper Python indentation
# document significant variables, especially inputs and outputs
# grade_1, grade_2, grade_3, average - id these
# year - id this
# fName, lName, ID, converted_ID
infile = open("studentinfo.txt", "r")
# you didn't 'intialize' this variable
data = infile.read()
# nor this
fName, lName, ID, year = data.split(",")
# this will produce an error if the file does not have the right number of strings
# 'year' is now a string, even though you 'initialized' it as 0
year = int(year)
# now 'year' is an integer
# a language that requires initialization would have raised an error
# over this switch in type of this variable.
# Prompt the user for three test scores
grades = eval(input("Enter the three test scores separated by a comma: "))
# 'eval' ouch!
# you could have handled the input just like you did the file input.
grade_1, grade_2, grade_3 = grades
# this would work only if the user gave you an 'iterable' with 3 values
# eval() doesn't ensure that it is an iterable
# and it does not ensure that the values are numbers.
# What would happen with this user input: "'one','two','three',4"?
# Create a username
uName = (lName[:4] + fName[:2] + str(year)).lower()
converted_id = ID[:3] + "-" + ID[3:5] + "-" + ID[5:]
# earlier you 'initialized' converted_ID
# initialization in a static typed language would have caught this typo
# pseudo-initialization in Python does not catch typos
....
You can try like this :
input[placeholder] {
text-align: center;
}
Carry Flag is a flag set when:
a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.
b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.
Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)
Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.
You can read more about flags on wikipedia
This only happens inside my load/unit testing projects. Frustrating, I jyst had it crop up in a project I have been running for 2 years. Must have been some order of test running that breaks things. I guess once that fi gets removed its gone.
I found that simply declaring a variable that uses the correct value fixes the issue... I never even call the method. Just define it. Odd but it works.
/// <summary> /// So that the test runner copies dlls not directly referenced by the integration project /// </summary> private void referenceLibs() { var useless = SqlProviderServices.Instance; }
secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text.
It's not valid XHTML to have to have nested forms. However, you can use multiple submit buttons and use a serverside script to run different codes depending on which button the users has clicked.
.disabled{ pointer-events: none }
will disable the click event, but not the tab event. To disable the tab event, you can set the tabindex to -1 if the disable flag is true.
<li [routerLinkActive]="['active']" [class.disabled]="isDisabled">
<a [routerLink]="['link']" tabindex="{{isDisabled?-1:0}}" > Menu Item</a>
</li>
If you want PHP to treat $_GET['select2']
as an array of options just add square brackets to the name of the select element like this: <select name="select2[]" multiple …
Then you can acces the array in your PHP script
<?php
header("Content-Type: text/plain");
foreach ($_GET['select2'] as $selectedOption)
echo $selectedOption."\n";
$_GET
may be substituted by $_POST
depending on the <form method="…"
value.
The above answers do not handle blank/undefined values to fix this I used the below code and replaced blanks with NA :
function getMax(dateArray, filler) {
filler= filler?filler:"";
if (!dateArray.length) {
return filler;
}
var max = "";
dateArray.forEach(function(date) {
if (date) {
var d = new Date(date);
if (max && d.valueOf()>max.valueOf()) {
max = d;
} else if (!max) {
max = d;
}
}
});
return max;
};
console.log(getMax([],"NA"));
console.log(getMax(datesArray,"NA"));
console.log(getMax(datesArray));
function getMin(dateArray, filler) {
filler = filler ? filler : "";
if (!dateArray.length) {
return filler;
}
var min = "";
dateArray.forEach(function(date) {
if (date) {
var d = new Date(date);
if (min && d.valueOf() < min.valueOf()) {
min = d;
} else if (!min) {
min = d;
}
}
});
return min;
}
console.log(getMin([], "NA"));
console.log(getMin(datesArray, "NA"));
console.log(getMin(datesArray));
I have added a plain javascript demo here and used it as a filter with AngularJS in this codepen
ASP.NET WebForms doesn't work this way. What you have above is just normal HTML, so ASP.NET isn't going to give you any facility to add/remove items. What you'll want to do is use a Repeater control, or possibly a GridView. These controls will be available in the code-behind. For example, the Repeater would expose an "Items" property upon which you can add new items (rows). In the code-front (the .aspx file) you'd provide an ItemTemplate that stubs out what the body rows would look like. There are plenty of tutorials on the web for repeaters, so I suggest you google that to obtain further information.
jQuery.fn.make_me_red = function() {
alert($(this).attr('id'));
$(this).siblings("#hello").toggle();
}
$("#user_button").click(function(){
//$(this).siblings(".hello").make_me_red();
$(this).make_me_red();
$(this).addClass("active");
});
?
Function declaration and callback in jQuery.
A good hash function should
A prime number modulus does not satisfy any of these points. It is simply insufficient. It is often better than nothing, but it's not even fast. Multiplying with an unsigned integer and taking a power-of-two modulus distributes the values just as well, that is not well at all, but with only about 2 cpu cycles it is much faster than the 15 to 40 a prime modulus will take (yes integer division really is that slow).
To create a hash function that is fast and distributes the values well the best option is to compose it from fast permutations with lesser qualities like they did with PCG for random number generation.
Useful permutations, among others, are:
Following this recipe we can create our own hash function or we take splitmix which is tested and well accepted.
If cryptographic qualities are needed I would highly recommend to use a function of the sha family, which is well tested and standardised, but for educational purposes this is how you would make one:
First you take a good non-cryptographic hash function, then you apply a one-way function like exponentiation on a prime field or k
many applications of (n*(n+1)/2) mod 2^k
interspersed with an xorshift when k
is the number of bits in the resulting hash.
Generally, I find RandomUtils (from Apache commons lang) an easier way to generate random numbers than java.util.Random
Look at the user and host column of your permission. Where you are coming from localhost or some other IPs do make a difference.
I thought I would add some extra bits, for tips and tricks that have come up.
One question I see come up a fair bit, is How do I get non-matching rows from two tables and I see the answer most commonly accepted as something like the following (based on our cars and brands table - which has Holden listed as a brand, but does not appear in the cars table):
select
a.ID,
a.brand
from
brands a
where
a.ID not in(select brand from cars)
And yes it will work.
+----+--------+
| ID | brand |
+----+--------+
| 6 | Holden |
+----+--------+
1 row in set (0.00 sec)
However it is not efficient in some database. Here is a link to a Stack Overflow question asking about it, and here is an excellent in depth article if you want to get into the nitty gritty.
The short answer is, if the optimiser doesn't handle it efficiently, it may be much better to use a query like the following to get non matched rows:
select
a.brand
from
brands a
left join cars b
on a.id=b.brand
where
b.brand is null
+--------+
| brand |
+--------+
| Holden |
+--------+
1 row in set (0.00 sec)
Ahhh, another oldie but goodie - the old You can't specify target table 'brands' for update in FROM clause.
MySQL will not allow you to run an update...
query with a subselect on the same table. Now, you might be thinking, why not just slap it into the where clause right? But what if you want to update only the row with the max()
date amoung a bunch of other rows? You can't exactly do that in a where clause.
update
brands
set
brand='Holden'
where
id=
(select
id
from
brands
where
id=6);
ERROR 1093 (HY000): You can't specify target table 'brands'
for update in FROM clause
So, we can't do that eh? Well, not exactly. There is a sneaky workaround that a surprisingly large number of users don't know about - though it does include some hackery that you will need to pay attention to.
You can stick the subquery within another subquery, which puts enough of a gap between the two queries so that it will work. However, note that it might be safest to stick the query within a transaction - this will prevent any other changes being made to the tables while the query is running.
update
brands
set
brand='Holden'
where id=
(select
id
from
(select
id
from
brands
where
id=6
)
as updateTable);
Query OK, 0 rows affected (0.02 sec)
Rows matched: 1 Changed: 0 Warnings: 0
Seems to work here:
>>> a=[[1,1],[2,1],[3,1]]
>>> a
[[1, 1], [2, 1], [3, 1]]
>>> a[1]
[2, 1]
>>> a[1][0]
2
>>> a[1][1]
1
I'm no expert, but I do believe that the null
equivalent for an int is 0
.
For example, if you make an int[]
, each slot contains 0
as opposed to null
, unless you set it to something else.
In some situations, this may be of use.
wrap your entire code block in this:
//<![CDATA[
//code here
//]]>
also make sure to specify the type of script to be text/javascript
try that and let me know how it goes
Note: Note to Win32 Users In order to enable this module (cURL) on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.
This note solved my problem. Thought of sharing. libeay32.dll & ssleay.dll you will find in your php installation folder.
Code for WebTestPlugIn
public class Protocols : WebTestPlugin
{
public override void PreRequest(object sender, PreRequestEventArgs e)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
}
Look at Process.Start and Process.StartInfo
This is merely an educated guess without seeing the rest of your HTML/CSS:
Have you applied display: block
or display: inline-block
to li a
? If not, try it.
Otherwise, try applying the CSS3 transform rules to li
instead.
In my side, it is because POSTMAN setting issue, but I don't know why, maybe I copy a query from other. I simply create a new request in POSTMAN and run it, it works.
In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution
[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
// Login logic
}
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:
try:
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
print 'Houston, we have a problem.'
raise
Which gives the following output that includes the offending statement and line number:
Houston, we have a problem.
Traceback (most recent call last):
File "/tmp/poop.py", line 2, in <module>
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie
Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):
import logging
try:
assert False == True
except AssertionError:
logging.error("Nothing is real but I can't quit...", exc_info=True)
The better way to handle null in the string is,
str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()
In short,
str.length()>0 && !str.equalsIgnoreCase("null")
A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.
Here's some code to illustrate. A point is time is captured in three different ways.
var moment = require( 'moment' );
var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );
//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );
//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate = ' + utcDate );
//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );
Which outputs this:
localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570
In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).
As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!
Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.
Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate )
, and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log
calls in the example.
I also experienced that for example:
This code doesnt work and get the intended block error.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
However, when i press tab before typing return self.title statement, the code works.
class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()
def __unicode__(self):
return self.title
Hope, this will help others.
If you are a python
user -
Create a requirements.txt
file preferably using pip freeze > requirements.txt
.
Add, commit and try pushing it again.
If this doesn't work try deleting .git
(beware this might remove the associated git history) and follow the above steps again.
Worked for me.
These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
Simple Working Example of Http request using node.
const http = require('https')
exports.handler = async (event) => {
return httprequest().then((data) => {
const response = {
statusCode: 200,
body: JSON.stringify(data),
};
return response;
});
};
function httprequest() {
return new Promise((resolve, reject) => {
const options = {
host: 'jsonplaceholder.typicode.com',
path: '/todos',
port: 443,
method: 'GET'
};
const req = http.request(options, (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
return reject(new Error('statusCode=' + res.statusCode));
}
var body = [];
res.on('data', function(chunk) {
body.push(chunk);
});
res.on('end', function() {
try {
body = JSON.parse(Buffer.concat(body).toString());
} catch(e) {
reject(e);
}
resolve(body);
});
});
req.on('error', (e) => {
reject(e.message);
});
// send the request
req.end();
});
}
Specifically for SQL-SERVER you can achieve that in many different ways.For given real example we took Customer table here.
Example 1: With "SET ROWCOUNT"
SET ROWCOUNT 10
SELECT CustomerID, CompanyName from Customers
ORDER BY CompanyName
To return all rows, set ROWCOUNT to 0
SET ROWCOUNT 0
SELECT CustomerID, CompanyName from Customers
ORDER BY CompanyName
Example 2: With "ROW_NUMBER and OVER"
With Cust AS
( SELECT CustomerID, CompanyName,
ROW_NUMBER() OVER (order by CompanyName) as RowNumber
FROM Customers )
select *
from Cust
Where RowNumber Between 0 and 10
Example 3 : With "OFFSET and FETCH", But with this "ORDER BY" is mandatory
SELECT CustomerID, CompanyName FROM Customers
ORDER BY CompanyName
OFFSET 0 ROWS
FETCH NEXT 10 ROWS ONLY
Hope this helps you.
It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
I had the same error, but I had it fixed by modifying the php.ini
file.
Find your php.ini file see Dude, where's my php.ini?
then open it with your favorite editor.
Look for a short_open_tag
property, and apply the following change:
; short_open_tag = Off ; previous value
short_open_tag = On ; new value
I was getting e.data.indexOf is not a function
error, after debugging it, I found that it was actually a TypeError
, which meant, indexOf()
being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf()
method to make it work
e.data.toString().indexOf('<stringToBeMatchedToPosition>')
Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.
(~~a == a)
where a
is the string.
the simplest way what I found from a tutorial of "TraversyMedia" is that just use https://cors-anywhere.herokuapp.com in 'axios' or 'fetch' api
https://cors-anywhere.herokuapp.com/{type_your_url_here}
e.g.
axios.get(`https://cors-anywhere.herokuapp.com/https://www.api.com/`)
and in your case edit url as
url: 'https://cors-anywhere.herokuapp.com/https://www.api.com',
You can use str_pad
for adding 0's
str_pad($month, 2, '0', STR_PAD_LEFT);
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
To create elements with equal width using Flex
, you should set to your's child (flex elements):
flex-basis: 25%;
flex-grow: 0;
It will give to all elements in row 25% width. They will not grow and go one by one.
Suppose your drop down list is:
<asp:DropDownList runat="server" id="ddl">
<asp:ListItem Value="0" text="Select a Value">
....
</asp:DropDownList>
There are two ways:
<asp:RequiredFieldValidator ID="re1" runat="Server" InitialValue="0" />
the 2nd way is to use a compare validator:
<asp:CompareValidator ID="re1" runat="Server" ValueToCompare="0" ControlToCompare="ddl" Operator="Equal" />
$order = new WC_Order(get_query_var('order-received'));
One simple approach is to check if unicode
is a builtin function. If so, you're in Python 2 and your string will be a string. To ensure everything is in unicode
one can do:
import builtins
i = 'cats'
if 'unicode' in dir(builtins): # True in python 2, False in 3
i = unicode(i)
I've tried all the above solutions, but none of them worked for me. The following code helped me, when trying to return to MainActivity in a way that onCreate gets called:
Intent.FLAG_ACTIVITY_CLEAR_TOP is the key.
@Override
public void onBackPressed() {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
Two options that don't require copying the whole set:
for e in s:
break
# e is now an element from s
Or...
e = next(iter(s))
But in general, sets don't support indexing or slicing.
What does the UDF EntityHasProfile() do?
Typically you could do something like this with a LEFT JOIN:
SELECT EntityId, EntityName, CASE WHEN EntityProfileIs IS NULL THEN 0 ELSE 1 END AS Has Profile
FROM Entities
LEFT JOIN EntityProfiles
ON EntityProfiles.EntityId = Entities.EntityId
This should eliminate a need for a costly scalar UDF call - in my experience, scalar UDFs should be a last resort for most database design problems in SQL Server - they are simply not good performers.
git diff branch_1..branch_2
That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
git diff branch_1...branch_2
In support of unwind, remember that Objective-C is a superset of C, rather than a completely new language.
Anything you can do in regular old ANSI C can be done in Objective-C.
Try this
Sheets("your sheetname").range("A5:X50").Value = ""
You can also use
ActiveSheet.range
$(document).ready( function() {
// Check All
$('.checkall').click(function () {
$(":checkbox").attr("checked", true);
});
// Uncheck All
$('.uncheckall').click(function () {
$(":checkbox").attr("checked", false);
});
});
Here's a quick one-line hack that I occasionally use to temporarily turn on log4j debug logging in a JUnit test:
Logger.getRootLogger().setLevel(Level.DEBUG);
or if you want to avoid adding imports:
org.apache.log4j.Logger.getRootLogger().setLevel(
org.apache.log4j.Level.DEBUG);
Note: this hack doesn't work in log4j2 because setLevel
has been removed from the API, and there doesn't appear to be equivalent functionality.
You can associate the same value with many keys, or just remove a key and re-add a new key with the same value.
For example, if you have keys->values:
red->1
blue->2
green->4
there's no reason you can't add purple->2
or remove red->1
and add orange->1
yes GPS settings cannot be changed programatically any more as they are privacy settings and we have to check if they are switched on or not from the program and handle it if they are not switched on. you can notify the user that GPS is turned off and use something like this to show the settings screen to the user if you want.
Check if location providers are available
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null){
Log.v(TAG, " Location providers: "+provider);
//Start searching for location and update the location text when update available
startFetchingLocation();
}else{
// Notify users and show settings if they want to enable GPS
}
If the user want to enable GPS you may show the settings screen in this way.
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE);
And in your onActivityResult you can see if the user has enabled it or not
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_CODE && resultCode == 0){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null){
Log.v(TAG, " Location providers: "+provider);
//Start searching for location and update the location text when update available.
// Do whatever you want
startFetchingLocation();
}else{
//Users did not switch on the GPS
}
}
}
Thats one way to do it and i hope it helps. Let me know if I am doing anything wrong.
Using strtotime() function you can easily convert date to timestamp
<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');
//define date and time
$date = date("d M Y H:i:s");
// output
echo strtotime($date);
?>
More info: http://php.net/manual/en/function.strtotime.php
Online conversion tool: http://freeonlinetools24.com/
This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).
To avoid it, the browser check the Same-origin policy
Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:
I also thought this would work but it's misleading:
myStruct _m1 = {0};
When I tried this:
myStruct _m1 = {0xff};
Only the 1st byte was set to 0xff
, the remaining ones were set to 0
. So I wouldn't get into the habit of using this.
Set the position to absolute; to move the caption area in the correct position
CSS
.post-content {
background: none repeat scroll 0 0 #FFFFFF;
opacity: 0.5;
margin: -54px 20px 12px;
position: absolute;
}
<em>
element - from W3C (HTML5 reference)YES! There is a clear difference.
The <em>
element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em>
elements.
<strong> = important content
<em> = stress emphasis of its contents
The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.
The <em>
element also isnt intended to convey importance; for that
purpose, the <strong>
element is more appropriate.
The <em>
element isn't a generic "italics" element. Sometimes, text
is intended to stand out from the rest of the paragraph, as if it was
in a different mood or voice. For this, the i
element is more
appropriate.
Reference (examples): See W3C Reference
This works in MySQL all versions and Amazon RDS Aurora:
INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
or
Setting the index column to NULL and then doing the INSERT.
But not in MariaDB, I tested version 10.