This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib
To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.
However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize
using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.
You have declared your Class as:
@Table( name = "foobar" )
public class FooBar {
You need to write the Class Name for the search.
from FooBar
If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.
I was facing the same issue. I realised that I was using the Wrong provider class in persistence.xml
For Hibernate it should be
<provider>org.hibernate.ejb.HibernatePersistence</provider>
And for EclipseLink it should be
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
In case you are using Spring Data Rest, issue can be resolved by creating Repositories for every Entity involved in cyclical references.
Not necessarily in all cases.
I m using Jboss 7.0.8 and Eclipselink 2.7.0. In my case to load entities without adding the same in persistence.xml, I added the following system property in Jboss Standalone XML:
<property name="eclipselink.archive.factory" value="org.jipijapa.eclipselink.JBossArchiveFactoryImpl"/>
In my case, previously I use idea to generate entity by database schema, and the persistence.xml
is automatically generated in src/main/java/META-INF
,and according to https://stackoverflow.com/a/23890419/10701129, I move it to src/main/resources/META-INF
, also marked META-INF as source root. It works for me.
But just simply marking original META-INF(that is, src/main/java/META-INF) as source root, doesn't work, which confuses me.
This may be old, but if anyone has the same problem try changing unitname to just name in the PersistenceContext annotation:
From
@PersistenceContext(unitName="educationPU")
to
@PersistenceContext(name="educationPU")
You might try changing this line in your persistence.xml from
<property name="hbm2ddl.auto" value="create"/>
to:
<property name="hibernate.hbm2ddl.auto" value="update"/>
This is supposed to maintain the schema to follow any changes you make to the Model each time you run the app.
Got this from JavaRanch
I needed to know how to get the actual error code number.
I inherited a project from someone else and I had to get the error codes from a .catch
clause that they had previously setup for Alamofire:
} .catch { (error) in
guard let error = error as? AFError else { return }
guard let statusCode = error.responseCode else { return }
print("Alamofire statusCode num is: ", statusCode)
}
Or if you need to get it from the response
value follow @mbryzinski's answer
Alamofire ... { (response) in
guard let error = response.result.error as? AFError else { return }
guard let statusCode = error.responseCode else { return }
print("Alamofire statusCode num is: ", statusCode)
})
If you want to disable particular date(s) in jquery datepicker then here is the simple demo for you.
<script type="text/javascript">
var arrDisabledDates = {};
arrDisabledDates[new Date("08/28/2017")] = new Date("08/28/2017");
arrDisabledDates[new Date("12/23/2017")] = new Date("12/23/2017");
$(".datepicker").datepicker({
dateFormat: "dd/mm/yy",
beforeShowDay: function (date) {
var day = date.getDay(),
bDisable = arrDisabledDates[date];
if (bDisable)
return [false, "", ""]
}
});
</script>
I want to leave this here because I struggled with this when compiling for Android in Windows with the Android SDK.
CMake distinguishes between TARGET and HOST platform.
My TARGET was Android so the variables like CMAKE_SYSTEM_NAME had the value "Android" and the variable WIN32 from the other answer here was not defined. But I wanted to know if my HOST system was Windows because I needed to do a few things differently when compiling on either Windows or Linux or IOs. To do that I used CMAKE_HOST_SYSTEM_NAME which I found is barely known or mentioned anywhere because for most people TARGEt and HOST are the same or they don't care.
Hope this helps someone somewhere...
What you should use is the errorLabelContainer
jQuery(function($) {_x000D_
var validator = $('#form').validate({_x000D_
rules: {_x000D_
first: {_x000D_
required: true_x000D_
},_x000D_
second: {_x000D_
required: true_x000D_
}_x000D_
},_x000D_
messages: {},_x000D_
errorElement : 'div',_x000D_
errorLabelContainer: '.errorTxt'_x000D_
});_x000D_
});
_x000D_
.errorTxt{_x000D_
border: 1px solid red;_x000D_
min-height: 20px;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
<input type="text" name="first" />_x000D_
<input type="text" name="second" />_x000D_
<div class="errorTxt"></div>_x000D_
<input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
If you want to retain your structure then
jQuery(function($) {_x000D_
var validator = $('#form').validate({_x000D_
rules: {_x000D_
first: {_x000D_
required: true_x000D_
},_x000D_
second: {_x000D_
required: true_x000D_
}_x000D_
},_x000D_
messages: {},_x000D_
errorPlacement: function(error, element) {_x000D_
var placement = $(element).data('error');_x000D_
if (placement) {_x000D_
$(placement).append(error)_x000D_
} else {_x000D_
error.insertAfter(element);_x000D_
}_x000D_
}_x000D_
});_x000D_
});
_x000D_
#errNm1 {_x000D_
border: 1px solid red;_x000D_
}_x000D_
#errNm2 {_x000D_
border: 1px solid green;_x000D_
}
_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>_x000D_
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>_x000D_
_x000D_
<form id="form" method="post" action="">_x000D_
<input type="text" name="first" data-error="#errNm1" />_x000D_
<input type="text" name="second" data-error="#errNm2" />_x000D_
<div class="errorTxt">_x000D_
<span id="errNm2"></span>_x000D_
<span id="errNm1"></span>_x000D_
</div>_x000D_
<input type="submit" class="button" value="Submit" />_x000D_
</form>
_x000D_
IF EXIST "somefile.txt" (
IF EXIST "someotherfile.txt" (
SET var="somefile.txt","someotherfile.txt"
)
) ELSE (
CALL :SUB
)
:SUB
ECHO Sorry... nothin' there.
GOTO:EOF
Is this feasible?
SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST "somefile.txt" (
SET var="somefile.txt"
IF EXIST "someotherfile.txt" (
SET var=!var!,"someotherfile.txt"
)
) ELSE (
IF EXIST "someotherfile.txt" (
SET var="someotherfile.txt"
) ELSE (
GOTO:EOF
)
)
An optional prefix
!
which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.
http://schacon.github.com/git/gitignore.html
*.json
!spec/*.json
I solved this issue by correcting my JDBC code.
the correct JDBC string should be...
conection = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:xe","system","ishantyagi");
But the JDBC string I was using was ...
conection = DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:orcl","system","ishantyagi");
So, the mistake of specifying orcl instead of xe showed this error as the SID name was wrong.
Not sure about "Best Practices" for memory leaks in python, but python should clear it's own memory by it's garbage collector. So mainly I would start by checking for circular list of some short, since they won't be picked up by the garbage collector.
Quote your args in Testscript 1:
echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"
In MVC, View screen is calling method which is in Controller or Repository.cs and assigning return value to any control in CSHTML but that method is actually not implemented in .cs/controller, then CSHTML will throw the NULL parameter exception
On my remote machine, I had TensorFlow
installed via pip
and when I was importing it in ipython
the import was successful. Despite of that I still got the No module named tensorflow
error when I was running my scripts. The issue here was that I was running my scripts with sudo
, so the python
and tensorflow
paths were not visible to the root. When I ran my scripts without sudo
, everything worked.
lots of big companies dont even use your expiration date anymore because it causes auto-renewal of payments to be lost when cards are issued with new expiration dates and the same account number. This has been a huge problem in the service industry, so these companies have cornered the card issuers into processing payments w/o expiration dates to avoid this pitfall. Not many people know about this yet, so not all companies use this practice.
Sure is:
@media screen and (-webkit-min-device-pixel-ratio:0)
{
#element { properties:value; }
}
And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/
Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.
Also, these hacks may not be future proof.
Keep in mind that, when you do this, the filesystem could be out of space and you may create a zero-length file. This is catastrophic if you're doing something like writing out /etc/passwd files as part of system configuration management.
Note that in-place file editing like in the accepted answer will always truncate the file and write out the new file sequentially. There will always be a race condition where concurrent readers will see a truncated file. If the process is aborted for any reason (ctrl-c, OOM killer, system crash, power outage, etc) during the write then the truncated file will also be left over, which can be catastrophic. This is the kind of dataloss scenario which developers MUST consider because it will happen. For that reason, I think the accepted answer should most likely not be the accepted answer. At a bare minimum write to a tempfile and move/rename the file into place like the "simple" solution at the end of this answer.
You need to use an algorithm that:
Reads the old file and writes out to the new file. (You need to be careful about slurping entire files into memory).
Explicitly closes the new temporary file, which is where you may throw an exception because the file buffers cannot be written to disk because there is no space. (Catch this and cleanup the temporary file if you like, but you need to rethrow something or fail fairly hard at this point.
Fixes the file permissions and modes on the new file.
Renames the new file and drops it into place.
With ext3 filesystems you are guaranteed that the metadata write to move the file into place will not get rearranged by the filesystem and written before the data buffers for the new file are written, so this should either succeed or fail. The ext4 filesystem has also been patched to support this kind of behavior. If you are very paranoid you should call the fdatasync()
system call as a step 3.5 before moving the file into place.
Regardless of language, this is best practice. In languages where calling close()
does not throw an exception (Perl or C) you must explicitly check the return of close()
and throw an exception if it fails.
The suggestion above to simply slurp the file into memory, manipulate it and write it out to the file will be guaranteed to produce zero-length files on a full filesystem. You need to always use FileUtils.mv
to move a fully-written temporary file into place.
A final consideration is the placement of the temporary file. If you open a file in /tmp then you have to consider a few problems:
If /tmp is mounted on a different file system you may run /tmp out of space before you've written out the file that would otherwise be deployable to the destination of the old file.
Probably more importantly, when you try to mv
the file across a device mount you will transparently get converted to cp
behavior. The old file will be opened, the old files inode will be preserved and reopened and the file contents will be copied. This is most likely not what you want, and you may run into "text file busy" errors if you try to edit the contents of a running file. This also defeats the purpose of using the filesystem mv
commands and you may run the destination filesystem out of space with only a partially written file.
This also has nothing to do with Ruby's implementation. The system mv
and cp
commands behave similarly.
What is more preferable is to open a Tempfile in the same directory as the old file. This ensures that there will be no cross-device move issues. The mv
itself should never fail, and you should always get a complete and untruncated file. Any failures, such as device out of space, permission errors, etc., should be encountered during writing the Tempfile out.
The only downsides to the approach of creating the Tempfile in the destination directory are:
Here's some code that implements the full-algorithm (windows code is untested and unfinished):
#!/usr/bin/env ruby
require 'tempfile'
def file_edit(filename, regexp, replacement)
tempdir = File.dirname(filename)
tempprefix = File.basename(filename)
tempprefix.prepend('.') unless RUBY_PLATFORM =~ /mswin|mingw|windows/
tempfile =
begin
Tempfile.new(tempprefix, tempdir)
rescue
Tempfile.new(tempprefix)
end
File.open(filename).each do |line|
tempfile.puts line.gsub(regexp, replacement)
end
tempfile.fdatasync unless RUBY_PLATFORM =~ /mswin|mingw|windows/
tempfile.close
unless RUBY_PLATFORM =~ /mswin|mingw|windows/
stat = File.stat(filename)
FileUtils.chown stat.uid, stat.gid, tempfile.path
FileUtils.chmod stat.mode, tempfile.path
else
# FIXME: apply perms on windows
end
FileUtils.mv tempfile.path, filename
end
file_edit('/tmp/foo', /foo/, "baz")
And here is a slightly tighter version that doesn't worry about every possible edge case (if you are on Unix and don't care about writing to /proc):
#!/usr/bin/env ruby
require 'tempfile'
def file_edit(filename, regexp, replacement)
Tempfile.open(".#{File.basename(filename)}", File.dirname(filename)) do |tempfile|
File.open(filename).each do |line|
tempfile.puts line.gsub(regexp, replacement)
end
tempfile.fdatasync
tempfile.close
stat = File.stat(filename)
FileUtils.chown stat.uid, stat.gid, tempfile.path
FileUtils.chmod stat.mode, tempfile.path
FileUtils.mv tempfile.path, filename
end
end
file_edit('/tmp/foo', /foo/, "baz")
The really simple use-case, for when you don't care about file system permissions (either you're not running as root, or you're running as root and the file is root owned):
#!/usr/bin/env ruby
require 'tempfile'
def file_edit(filename, regexp, replacement)
Tempfile.open(".#{File.basename(filename)}", File.dirname(filename)) do |tempfile|
File.open(filename).each do |line|
tempfile.puts line.gsub(regexp, replacement)
end
tempfile.close
FileUtils.mv tempfile.path, filename
end
end
file_edit('/tmp/foo', /foo/, "baz")
TL;DR: That should be used instead of the accepted answer at a minimum, in all cases, in order to ensure the update is atomic and concurrent readers will not see truncated files. As I mentioned above, creating the Tempfile in the same directory as the edited file is important here to avoid cross device mv operations being translated into cp operations if /tmp is mounted on a different device. Calling fdatasync is an added layer of paranoia, but it will incur a performance hit, so I omitted it from this example since it is not commonly practiced.
Use the Instr function
Dim pos As Integer
pos = InStr("find the comma, in the string", ",")
will return 15 in pos
If not found it will return 0
If you need to find the comma with an excel formula you can use the =FIND(",";A1)
function.
Notice that if you want to use Instr
to find the position of a string case-insensitive use the third parameter of Instr and give it the const vbTextCompare
(or just 1 for die-hards).
Dim posOf_A As Integer
posOf_A = InStr(1, "find the comma, in the string", "A", vbTextCompare)
will give you a value of 14.
Note that you have to specify the start position in this case as stated in the specification I linked: The start argument is required if compare is specified.
Try this link.... horizontal rule
That should do the trick.
The code below is xml.
<View
android:layout_width="fill_parent"
android:layout_height="2dip"
android:background="#FF00FF00" />
Simply delete your local master branch and recreate it like so:
git branch -D master
git checkout origin/master -b master
You can take a look here for a longer list of screen sizes and respective media queries.
Or go for Bootstrap media queries:
/* Large desktop */
@media (min-width: 1200px) { ... }
/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }
/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }
/* Landscape phones and down */
@media (max-width: 480px) { ... }
Additionally you might wanty to take a look at Foundation's media queries with the following default settings:
// Media Queries
$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;
Visual Studio e.g. 2019 In general be aware that the selected Platform (e.g. x64) in the configuration Dialog is the the same as the Platform You intend to debug with! (see picture for explanation)
Greetings mic enter image description here
You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:
"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"
For Angular 2
<input [(ngModel)]='email' [required]='!phone' />
<input [(ngModel)]='phone' [required]='!email' />
I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:
<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">
but it should be:
<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">
Just change <scrip>
to <link>
and src
to href
Another possible fix:
For some reason, this work.
Vim requires the cursor to be in the current screen at all times, however, you could bookmark the current position scroll around and then return to where you were.
mg # This book marks the current position as g (this can be any letter)
<scroll around>
`g # return to g
The main difference between this answer and the accepted answer is the use of setViewportView()
instead of add()
.
How to put JTable
in JScrollPane
using Eclipse IDE:
JScrollPane
container via Design tab.JScrollPane
to desired size (applies to Absolute Layout).JTable
component on top of JScrollPane
(Viewport area).In Structure > Components, table
should be a child of scrollPane
.
The generated code would be something like this:
JScrollPane scrollPane = new JScrollPane();
...
JTable table = new JTable();
scrollPane.setViewportView(table);
For me xcode-select --reset
was the solution on Mojave.
You can try and check for the referer, which should be the parent site if you're an iframe
you can do that like this:
var href = document.referrer;
An implicitly declared function is one that has neither a prototype nor a definition, but is called somewhere in the code. Because of that, the compiler cannot verify that this is the intended usage of the function (whether the count and the type of the arguments match). Resolving the references to it is done after compilation, at link-time (as with all other global symbols), so technically it is not a problem to skip the prototype.
It is assumed that the programmer knows what he is doing and this is the premise under which the formal contract of providing a prototype is omitted.
Nasty bugs can happen if calling the function with arguments of a wrong type or count. The most likely manifestation of this is a corruption of the stack.
Nowadays this feature might seem as an obscure oddity, but in the old days it was a way to reduce the number of header files included, hence faster compilation.
Usually this can be done by using a function pointer, that is a special variable that points to the memory location of a function. You can then use this to call the function with specific arguments. So there will probably be a function that sets the callback function. This will accept a function pointer and then store that address somewhere where it can be used. After that when the specified event is triggered, it will call that function.
You are probably experiencing an issue with a firewall. The 'problem' is that the port you specify is not the only port used, it uses 1 or maybe even 2 more ports for RMI, and those are probably blocked by a firewall.
One of the extra ports will not be know up front if you use the default RMI configuration, so you have to open up a big range of ports - which might not amuse the server administrator.
There is a solution that does not require opening up a lot of ports however, I've gotten it to work using the combined source snippets and tips from
http://forums.sun.com/thread.jspa?threadID=5267091 - link doesn't work anymore
http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx
http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html
It's even possible to setup an ssh tunnel and still get it to work :-)
Check this out:
plt.hist(myarray, density = True)
For Windows, here's a link to an example batch file that only allows changes to the log message (not other properties):
http://ayria.livejournal.com/33438.html
Basically copy the code below into a text file and name it pre-revprop-change.bat
and save it in the \hooks
subdirectory for your repository.
@ECHO OFF
:: Set all parameters. Even though most are not used, in case you want to add
:: changes that allow, for example, editing of the author or addition of log messages.
set repository=%1
set revision=%2
set userName=%3
set propertyName=%4
set action=%5
:: Only allow the log message to be changed, but not author, etc.
if /I not "%propertyName%" == "svn:log" goto ERROR_PROPNAME
:: Only allow modification of a log message, not addition or deletion.
if /I not "%action%" == "M" goto ERROR_ACTION
:: Make sure that the new svn:log message is not empty.
set bIsEmpty=true
for /f "tokens=*" %%g in ('find /V ""') do (
set bIsEmpty=false
)
if "%bIsEmpty%" == "true" goto ERROR_EMPTY
goto :eof
:ERROR_EMPTY
echo Empty svn:log messages are not allowed. >&2
goto ERROR_EXIT
:ERROR_PROPNAME
echo Only changes to svn:log messages are allowed. >&2
goto ERROR_EXIT
:ERROR_ACTION
echo Only modifications to svn:log revision properties are allowed. >&2
goto ERROR_EXIT
:ERROR_EXIT
exit /b 1
If your device knows the Wifi configs (already stored), we can bypass rocket science. Just loop through the configs an check if the SSID is matching. If so, connect and return.
Set permissions:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Connect:
try {
String ssid = null;
if (wifi == Wifi.PCAN_WIRELESS_GATEWAY) {
ssid = AesPrefs.get(AesConst.PCAN_WIRELESS_SSID,
context.getString(R.string.pcan_wireless_ssid_default));
} else if (wifi == Wifi.KJ_WIFI) {
ssid = context.getString(R.string.remote_wifi_ssid_default);
}
WifiManager wifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
List<WifiConfiguration> wifiConfigurations = wifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfiguration : wifiConfigurations) {
if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) {
wifiManager.enableNetwork(wifiConfiguration.networkId, true);
Log.i(TAG, "connectToWifi: will enable " + wifiConfiguration.SSID);
wifiManager.reconnect();
return null; // return! (sometimes logcat showed me network-entries twice,
// which may will end in bugs)
}
}
} catch (NullPointerException | IllegalStateException e) {
Log.e(TAG, "connectToWifi: Missing network configuration.");
}
return null;
first use @Html.AntiForgeryToken() in html
$.ajax({
url: "@Url.Action("SomeMethod", "SomeController")",
type: 'POST',
data: JSON.stringify(jsonObject),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
beforeSend: function (request) {
request.setRequestHeader("RequestVerificationToken", $("[name='__RequestVerificationToken']").val());
},
success: function (msg) {
alert(msg);
}
task :build_all do
[ :debug, :release ].each do |t|
$build_type = t
Rake::Task["build"].reenable
Rake::Task["build"].invoke
end
end
That should sort you out, just needed the same thing myself.
Add the permissions to the app manifest
Add one of the following permissions as a child of the element in your Android manifest. Either the coarse location permission:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>
Or the fine location permission:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp" >
...
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
...
</manifest>
The following code sample checks for permission using the Support library before enabling the My Location layer:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
The following sample handles the result of the permission request by implementing the ActivityCompat.OnRequestPermissionsResultCallback from the Support library:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_LOCATION_REQUEST_CODE) {
if (permissions.length == 1 &&
permissions[0] == Manifest.permission.ACCESS_FINE_LOCATION &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Permission was denied. Display an error message.
}
}
This example provides current location update using GPS provider. Entire Android app code is as follows,
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
I had the same problem.
The cause for me was that the Command
option in Configuration Properties | Debugging
had been reset to its default value.
I hade this error when transfering a csv to mssql I converted the columns to DT_NTEXT and some columns on mssql where set to nvarchar(255).
setting them to nvarchar(max) resolved it.
Just finished up a js library for formatting numbers Numeral.js. It handles decimals, dollars, percentages and even time formatting.
Issue resolved.!!! Below are the solutions.
For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar
Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider
Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
Issue is that it is failed to decrypt 256 bits of encryption.
I found a solution that worked in my case:
<input class="form-control" style="min-width: 100%!important;" type="text" />
You only need to override the min-width set 100% and important and the result is this one:
If you don't apply it, you will always get this:
I highly recommend Loopj.
I have successfully used it to upload multiple files at once, including different mime types. Simply do this:
File myVideo = new File("/path/to/myvideo.mp4");
File myPic = new File("/path/to/mypic.jpg");
RequestParams params = new RequestParams();
try {
params.put("profile_picture", myPic);
params.put("my_video", myVideo);
} catch(FileNotFoundException e) {}
For large or many files you might have to increase the timeout amount else the default timeout is used which might be too short:
client.setTimeout(500000) //make this the appropriate timeout in milliseconds
Please see this links for a full description of loopj and how to use it, by far the easiest async http library I have come across:
http://loopj.com/android-async-http/ http://loopj.com/android-async-http/doc/com/loopj/android/http/AsyncHttpClient.html
There are already many answers. Anyway, I want to write what worked for me so it may help anyone to try.
I created a logback-test.xml within src/test/resources with the following:
<configuration>
<include resource="/org/springframework/boot/logging/logback/base.xml"/>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
Started build after this, Junit runner picked up the above mentioned log level "info" and there are no org.apache.http logs.
I had the same problem with small difference:
Exception was raised at the moment of flushing
It is a different stackoverflow issue. The brief explanation was a wrong response header setting:
response.setHeader("Content-Encoding", "gzip");
despite uncompressed response data content.
So the the connection was closed by the browser.
This happened to me when I tried to run an Activity
on 2.2 that used imports from Honeycomb not available in older versions of Android and not included in the v4 support package either.
Sending a json object from Android is easy if you use Apache HTTP Client. Here's a code sample on how to do it. You should create a new thread for network activities so as not to lock up the UI thread.
protected void sendJson(final String email, final String pwd) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch(Exception e) {
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
You could also use Google Gson to send and retrieve JSON.
Take a random sample without replacement of the indices, sort the indices, and take them from the original.
indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]
Or more concisely:
[x[1] for x in sorted(random.sample(enumerate(myList),K))]
You can alternatively use a math trick and iteratively go through myList
from left to right, picking numbers with dynamically-changing probability (N-numbersPicked)/(total-numbersVisited)
. The advantage of this approach is that it's an O(N)
algorithm since it doesn't involve sorting!
from __future__ import division
def orderedSampleWithoutReplacement(seq, k):
if not 0<=k<=len(seq):
raise ValueError('Required that 0 <= sample_size <= population_size')
numbersPicked = 0
for i,number in enumerate(seq):
prob = (k-numbersPicked)/(len(seq)-i)
if random.random() < prob:
yield number
numbersPicked += 1
Proof of concept and test that probabilities are correct:
Simulated with 1 trillion pseudorandom samples over the course of 5 hours:
>>> Counter(
tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
for _ in range(10**9)
)
Counter({
(0, 3): 166680161,
(1, 2): 166672608,
(0, 2): 166669915,
(2, 3): 166667390,
(1, 3): 166660630,
(0, 1): 166649296
})
Probabilities diverge from true probabilities by less a factor of 1.0001. Running this test again resulted in a different order meaning it isn't biased towards one ordering. Running the test with fewer samples for [0,1,2,3,4], k=3
and [0,1,2,3,4,5], k=4
had similar results.
edit: Not sure why people are voting up wrong comments or afraid to upvote... NO, there is nothing wrong with this method. =)
(Also a useful note from user tegan in the comments: If this is python2, you will want to use xrange, as usual, if you really care about extra space.)
edit: Proof: Considering the uniform distribution (without replacement) of picking a subset of k
out of a population seq
of size len(seq)
, we can consider a partition at an arbitrary point i
into 'left' (0,1,...,i-1) and 'right' (i,i+1,...,len(seq)). Given that we picked numbersPicked
from the left known subset, the remaining must come from the same uniform distribution on the right unknown subset, though the parameters are now different. In particular, the probability that seq[i]
contains a chosen element is #remainingToChoose/#remainingToChooseFrom
, or (k-numbersPicked)/(len(seq)-i)
, so we simulate that and recurse on the result. (This must terminate since if #remainingToChoose == #remainingToChooseFrom, then all remaining probabilities are 1.) This is similar to a probability tree that happens to be dynamically generated. Basically you can simulate a uniform probability distribution by conditioning on prior choices (as you grow the probability tree, you pick the probability of the current branch such that it is aposteriori the same as prior leaves, i.e. conditioned on prior choices; this will work because this probability is uniformly exactly N/k).
edit: Timothy Shields mentions Reservoir Sampling, which is the generalization of this method when len(seq)
is unknown (such as with a generator expression). Specifically the one noted as "algorithm R" is O(N) and O(1) space if done in-place; it involves taking the first N element and slowly replacing them (a hint at an inductive proof is also given). There are also useful distributed variants and miscellaneous variants of reservoir sampling to be found on the wikipedia page.
edit: Here's another way to code it below in a more semantically obvious manner.
from __future__ import division
import random
def orderedSampleWithoutReplacement(seq, sampleSize):
totalElems = len(seq)
if not 0<=sampleSize<=totalElems:
raise ValueError('Required that 0 <= sample_size <= population_size')
picksRemaining = sampleSize
for elemsSeen,element in enumerate(seq):
elemsRemaining = totalElems - elemsSeen
prob = picksRemaining/elemsRemaining
if random.random() < prob:
yield element
picksRemaining -= 1
from collections import Counter
Counter(
tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
for _ in range(10**5)
)
The above options works for Google big query file also. I exported a table data to goodle cloud storage and downloaded from there. While loading the same to sql server was facing this issue and could successfully load the file after specifying the row delimiter as
ROWTERMINATOR = '0x0a'
Pay attention to header record as well and specify
FIRSTROW = 2
My final block for data file export from google bigquery looks like this.
BULK INSERT TABLENAME
FROM 'C:\ETL\Data\BigQuery\In\FILENAME.csv'
WITH
(
FIRSTROW = 2,
FIELDTERMINATOR = ',', --CSV field delimiter
ROWTERMINATOR = '0x0a',--Files are generated with this row terminator in Google Bigquery
TABLOCK
)
Check this page http://www.alanwood.net/unicode/geometric_shapes.html, first is "9650 ? 25B2 BLACK UP-POINTING TRIANGLE (present in WGL4)" and 2nd "9660 ? 25BC BLACK DOWN-POINTING TRIANGLE (present in WGL4)".
I found out, that I need to set the public
property of devServer, to my request's host value. Being that it will be displayed at that external address.
So I needed this in my webpack.config.js
devServer: {
compress: true,
public: 'store-client-nestroia1.c9users.io' // That solved it
}
Another solution is using it on the CLI:
webpack-dev-server --public $C9_HOSTNAME <-- var for Cloud9 external IP
Python version supported by Django version
Django version Python versions
----------------------------------------
1.0 2.3, 2.4, 2.5, 2.6
1.1 2.3, 2.4, 2.5, 2.6
1.2 2.4, 2.5, 2.6, 2.7
1.3 2.4, 2.5, 2.6, 2.7
1.4 2.5, 2.6, 2.7
1.5 2.6.5, 2.7 and 3.2.3, 3.3 (experimental)
1.6 2.6.5, 2.7 and 3.2.3, 3.3
1.11 2.7, 3.4, 3.5, 3.6, 3.7 (added in 1.11.17)
2.0 3.4, 3.5, 3.6, 3.7
2.1, 2.2 3.5, 3.6, 3.7
To verify that Django can be seen by Python, type python
from your shell. Then at the Python prompt, try to import Django:
>>> import django
>>> print(django.get_version())
2.1
>>> django.VERSION
(2, 1, 4, 'final', 0)
It is SUBSTITUTE(B1," ","")
, not REPLACE(xx;xx;xx)
.
A (partial) practical work-around is to put things into a throw-away function.
Pasting
x = 1
x += 1
print(x)
results in
>>> x = 1
x += 1
print(x)
File "<stdin>", line 1
x += 1
print(x)
^
SyntaxError: multiple statements found while compiling a single statement
>>>
However, pasting
def abc():
x = 1
x += 1
print(x)
works:
>>> def abc():
x = 1
x += 1
print(x)
>>> abc()
2
>>>
Of course, this is OK for a quick one-off, won't work for everything you might want to do, etc. But then, going to ipython
/ jupyter qtconsole
is probably the next simplest option.
What exactly is the structure of your HTML?
The previous CSS will work if the HTML is as such:
CSS
.foo:nth-child(2)
HTML
<div>
<div class="foo"></div>
<div class="foo">Find me</div>
...
</div>
But if you have the following HTML it will not work.
<div>
<div class="other"></div>
<div class="foo"></div>
<div class="foo">Find me</div>
...
</div>
Simple put, there is no selector for the getting the index of the matches from the rest of the selector before it.
Run the app using the simulator
iOS Simulator-> Hardware-> Keyboard -> iOS uses same layout as OS X
This will fix the issue if anyone out there is running their app on their device
Both of the above answers assume that you only have one row for each user and time_stamp. Depending on the application and the granularity of your time_stamp this may not be a valid assumption. If you need to deal with ties of time_stamp for a given user, you'd need to extend one of the answers given above.
To write this in one query would require another nested sub-query - things will start getting more messy and performance may suffer.
I would have loved to have added this as a comment but I don't yet have 50 reputation so sorry for posting as a new answer!
[Twitter Bootstrap v3]
To create a n-level dropdown menu (touch device friendly) in Twitter Bootstrap v3,
CSS:
.dropdown-menu>li /* To prevent selection of text */
{ position:relative;
-webkit-user-select: none; /* Chrome/Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+ */
/* Rules below not implemented in browsers yet */
-o-user-select: none;
user-select: none;
cursor:pointer;
}
.dropdown-menu .sub-menu
{
left: 100%;
position: absolute;
top: 0;
display:none;
margin-top: -1px;
border-top-left-radius:0;
border-bottom-left-radius:0;
border-left-color:#fff;
box-shadow:none;
}
.right-caret:after,.left-caret:after
{ content:"";
border-bottom: 5px solid transparent;
border-top: 5px solid transparent;
display: inline-block;
height: 0;
vertical-align: middle;
width: 0;
margin-left:5px;
}
.right-caret:after
{ border-left: 5px solid #ffaf46;
}
.left-caret:after
{ border-right: 5px solid #ffaf46;
}
JQuery:
$(function(){
$(".dropdown-menu > li > a.trigger").on("click",function(e){
var current=$(this).next();
var grandparent=$(this).parent().parent();
if($(this).hasClass('left-caret')||$(this).hasClass('right-caret'))
$(this).toggleClass('right-caret left-caret');
grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
grandparent.find(".sub-menu:visible").not(current).hide();
current.toggle();
e.stopPropagation();
});
$(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
var root=$(this).closest('.dropdown');
root.find('.left-caret').toggleClass('right-caret left-caret');
root.find('.sub-menu:visible').hide();
});
});
HTML:
<div class="dropdown" style="position:relative">
<a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Click Here <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>
<a class="trigger right-caret">Level 1</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 2</a></li>
<li>
<a class="trigger right-caret">Level 2</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 3</a></li>
<li><a href="#">Level 3</a></li>
<li>
<a class="trigger right-caret">Level 3</a>
<ul class="dropdown-menu sub-menu">
<li><a href="#">Level 4</a></li>
<li><a href="#">Level 4</a></li>
<li><a href="#">Level 4</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Level 2</a></li>
</ul>
</li>
<li><a href="#">Level 1</a></li>
<li><a href="#">Level 1</a></li>
</ul>
</div>
One of the way to browse your database is to use questoid sqlite manager.
# 1. Download questoid manager from this link .
# 2. Drop this file into your eclipse --> dropins.
# 3. Restart your eclipse.
# 4. Now go to your file explorer and click your database. you can find a blue database icon enabled in the top right corner.
# 5. Double click the icon and you can see ur inserted fields/tables/ in the database
I always add this style to my Bootstrap LESS / SASS:
.row-no-padding {
[class*="col-"] {
padding-left: 0 !important;
padding-right: 0 !important;
}
}
Then in the HTML you can write:
<div class="row row-no-padding">
CHAR :
VARCHAR :
any comments......!!!!
Here is a well tested function which i used for my projects with detailed self explanatory comments
There are many times when the ports other than 80 are blocked by server firewall so the code appears to be working fine on localhost but not on the server
function get_page($url){
global $proxy;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HEADER, 0); // return headers 0 no 1 yes
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return page 1:yes
curl_setopt($ch, CURLOPT_TIMEOUT, 200); // http request timeout 20 seconds
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects, need this if the url changes
curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //if http server gives redirection responce
curl_setopt($ch, CURLOPT_USERAGENT,
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); // cookies storage / here the changes have been made
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // false for https
curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // the page encoding
$data = curl_exec($ch); // execute the http request
curl_close($ch); // close the connection
return $data;
}
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
As of Xcode 8 Objective-C now supports class properties:
@interface MyClass : NSObject
@property (class, nonatomic, assign, readonly) NSUUID* identifier;
@end
Since class properties are never synthesised you need to write your own implementation.
@implementation MyClass
static NSUUID*_identifier = nil;
+ (NSUUID *)identifier {
if (_identifier == nil) {
_identifier = [[NSUUID alloc] init];
}
return _identifier;
}
@end
You access the class properties using normal dot syntax on the class name:
MyClass.identifier;
You shouldn't need to. Allow the user to have whatever preferences they want.
Firefox does that by default because opening a page in a new window is annoying and a page should never be allowed to do so if that is not what is desired by the user. (Firefox does allow you to open tabs in a new window if you set it that way).
Please never do this in real projects:
document.getElementById("span").innerHTML = "String".fontsize(25);
_x000D_
<span id="span"></span>
_x000D_
Here is another interesting way of finding null and replacing with a calculated value
#Creating the DataFrame
testdf = pd.DataFrame({'Tenure':[1,2,3,4,5],'Monthly':[10,20,30,40,50],'Yearly':[10,40,np.nan,np.nan,250]})
>>> testdf2
Monthly Tenure Yearly
0 10 1 10.0
1 20 2 40.0
2 30 3 NaN
3 40 4 NaN
4 50 5 250.0
#Identifying the rows with empty columns
nan_rows = testdf2[testdf2['Yearly'].isnull()]
>>> nan_rows
Monthly Tenure Yearly
2 30 3 NaN
3 40 4 NaN
#Getting the rows# into a list
>>> index = list(nan_rows.index)
>>> index
[2, 3]
# Replacing null values with calculated value
>>> for i in index:
testdf2['Yearly'][i] = testdf2['Monthly'][i] * testdf2['Tenure'][i]
>>> testdf2
Monthly Tenure Yearly
0 10 1 10.0
1 20 2 40.0
2 30 3 90.0
3 40 4 160.0
4 50 5 250.0
Depending on your tool - you can also inject HTML into markdown.
<img src="./img/Isolated.png">
This assumes your folder structure is:
+-- img
+-- Isolated.jpg
+-- README.md
For me, the problem was the use of Java 1.8 in a module, but not in the app module. I added this to the app build gradle and worked:
android{
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
according to http://mylinuxbook.com/hexdump/ you might use the hexdump format parameter
echo Aa | hexdump -C -e '/1 "%02X"'
will return 4161
to add an extra linefeed at the end, append another formatter.
BUT: the format given above will give multiplier outputs for repetitive characters
$ printf "Hello" | hexdump -e '/1 "%02X"'
48656C*
6F
instead of
48656c6c6f
There are several different varieties of CRC-16. See wiki page.
Every of those will return different results from the same input.
So you must carefully select correct one for your program.
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
Microsoft Excel for Mac 2011 v 14.5.9
This is how I did it:
EntityManager entityManager = getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
long id = object.getId();
entityManager.close();
I had the same problem. But in my case, the Debuggable
attribute was hard coded in the AssemblyInfo.cs
file of my project and therefor not (over-)written by compilation. It worked after removing the line specifying the Debuggable
attribute.
You can access your log files using Heroku's Command Line Interface (CLI Usage).
If Heroku's CLI is installed and you know your application name (like https://myapp.herokuapp.com/
), then you can run the following command:
heroku logs --tail --app=myapp
You can also access the logs in a real-time stream using:
heroku logs --source app --tail --app=myapp
If the logs tell you something like this:
npm ERR! A complete log of this run can be found in:
npm ERR! /app/.npm/_logs/2017-07-11T08_29_45_291Z-debug.log
Then you can also access them using the bash terminal via Heroku CLI:
heroku run bash --app=myapp
less ./.npm/_logs/2017-07-11T08_29_45_291Z-debug.log
I created a blank MS Document with Landscape setting and then opened it in notepad. Copied and pasted the following to my html page
<style type="text/css" media="print">
@page Section1
{size:11 8.5in;
margin:.5in 13.6pt 0in 13.6pt;
mso-header-margin:.5in;
mso-footer-margin:.5in;
mso-paper-source:4;}
div.Section1
{page:Section1;}
</style>
<div class="Section1"> put text / images / other stuff </div>
The print preview shows the pages in a landscape size. This seems to be working fine on IE and Chrome, not tested on FF.
Do a "recursive" setTimeout
of your function, and it will keep being executed every amount of time defined:
function yourFunction(){
// do whatever you like here
setTimeout(yourFunction, 5000);
}
yourFunction();
you can read this tutorial for how to use functions of statistical distributions in python. http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html
from scipy.stats import norm
import matplotlib.pyplot as plt
import numpy as np
#initialize a normal distribution with frozen in mean=-1, std. dev.= 1
rv = norm(loc = -1., scale = 1.0)
rv1 = norm(loc = 0., scale = 2.0)
rv2 = norm(loc = 2., scale = 3.0)
x = np.arange(-10, 10, .1)
#plot the pdfs of these normal distributions
plt.plot(x, rv.pdf(x), x, rv1.pdf(x), x, rv2.pdf(x))
If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.
HTML:
<body>
<div id="content">...</div>
</body>
CSS:
#content {
max-width: 1000px;
margin: auto;
left: 1%;
right: 1%;
position: absolute;
}
JavaScript (using jQuery):
$(function() {
$(window).on('resize', function resize() {
$(window).off('resize', resize);
setTimeout(function () {
var content = $('#content');
var top = (window.innerHeight - content.height()) / 2;
content.css('top', Math.max(0, top) + 'px');
$(window).on('resize', resize);
}, 50);
}).resize();
});
I got the upload working with above changes. But when I made the changes I started getting 404 response in file upload which lead me to do further debugging and figured out its a permission issue by checking nginx error.log
Solution:
Check the current user and group ownership on /var/lib/nginx.
$ ls -ld /var/lib/nginx
drwx------. 3 nginx nginx 17 Oct 5 19:31 /var/lib/nginx
This tells that a possibly non-existent user and group named nginx owns this folder. This is preventing file uploading.
In my case, the username mentioned in "/etc/nginx/nginx.conf" was
user vagrant;
Change the folder ownership to the user defined in nginx.conf in this case vagrant.
$ sudo chown -Rf vagrant:vagrant /var/lib/nginx
Verify that it actually changed.
$ ls -ld /var/lib/nginx
drwx------. 3 vagrant vagrant 17 Oct 5 19:31 /var/lib/nginx
Reload nginx and php-fpm for safer sade.
$ sudo service nginx reload
$ sudo service php-fpm reload
The permission denied error should now go away. Check the error.log (based on nginx.conf error_log location).
$ sudo nano /path/to/nginx/error.log
Certainly the credit goes to @Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.
Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.
using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
foreach(var u in users)
{
DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
}
}
I am running CentOS 5.6 as my development environment and the following worked for me.
su -
pecl install ssh2
echo "extension=ssh2.so" > /etc/php.d/ssh2.ini
/etc/init.d/httpd restart
Not sure why the code above did not work for the library rgl
, but the following link has a great example with the same library.
Run the code in R and you will obtain a beautiful 3d plot that you can turn around in all angles.
http://statisticsr.blogspot.de/2008/10/some-r-functions.html
########################################################################
## another example of 3d plot from my personal reserach, use rgl library
########################################################################
# 3D visualization device system
library(rgl);
data(volcano)
dim(volcano)
peak.height <- volcano;
ppm.index <- (1:nrow(volcano));
sample.index <- (1:ncol(volcano));
zlim <- range(peak.height)
zlen <- zlim[2] - zlim[1] + 1
colorlut <- terrain.colors(zlen) # height color lookup table
col <- colorlut[(peak.height-zlim[1]+1)] # assign colors to heights for each point
open3d()
ppm.index1 <- ppm.index*zlim[2]/max(ppm.index);
sample.index1 <- sample.index*zlim[2]/max(sample.index)
title.name <- paste("plot3d ", "volcano", sep = "");
surface3d(ppm.index1, sample.index1, peak.height, color=col, back="lines", main = title.name);
grid3d(c("x", "y+", "z"), n =20)
sample.name <- paste("col.", 1:ncol(volcano), sep="");
sample.label <- as.integer(seq(1, length(sample.name), length = 5));
axis3d('y+',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3);
axis3d('y',at = sample.index1[sample.label], sample.name[sample.label], cex = 0.3)
axis3d('z',pos=c(0, 0, NA))
ppm.label <- as.integer(seq(1, length(ppm.index), length = 10));
axes3d('x', at=c(ppm.index1[ppm.label], 0, 0), abs(round(ppm.index[ppm.label], 2)), cex = 0.3);
title3d(main = title.name, sub = "test", xlab = "ppm", ylab = "samples", zlab = "peak")
rgl.bringtotop();
The below function would return '0' if there is no match and a 'positive integer' in case of matching:
Function IsInArray(stringToBeFound As String, arr As Variant) As Integer
IsInArray = InStr(Join(arr, ""), stringToBeFound)
End Function
______________________________________________________________________________
Note: the function first concatenates the entire array content to a string using 'Join' (not sure if the join method uses looping internally or not) and then checks for a macth within this string using InStr.
in Package Manager Console, just Type Remove-Migration And Press Enter. It automatically removes the migration.
Tools -> Nuget Package Manager -> Package Manager Console
I realize that this question is quite old but I had a similar issue. The following did what I wanted:
class Agent(object):
_agents = dict()
def __new__(cls, *p):
number = p[0]
if not number in cls._agents:
cls._agents[number] = object.__new__(cls)
return cls._agents[number]
def __init__(self, number):
self.number = number
def __eq__(self, rhs):
return self.number == rhs.number
Agent("a") is Agent("a") == True
I used this page as a resource http://infohost.nmt.edu/tcc/help/pubs/python/web/new-new-method.html
You ran into Eclipse bug 525948 which has already been fixed and which will be published in the upcoming release Oxygen.3 (4.7.3), March 21, 2018.
As workaround, put your test code in a separate project and add the project under test to the modulepath, but do not add a module-info.java
to your test project. With your project, class and module naming, it should look something like this:
See also my video that shows Java 9 and JUnit 5 in Eclipse Oxygen.1a in action
First add the new files:
svn add fileName
Then commit all new and modified files
svn ci <files_separated_by_space> -m "Commit message|ReviewID:XXXX"
If non source files are to be committed then
svn ci <files> -m "Commit msg|ReviewID:NON-SOURCE"
Most upvoted answer is probably the best way to get the timezone, however, Intl.DateTimeFormat().resolvedOptions().timeZone
returns IANA timezone name by definition, which is in English.
If you want the timezone's name in current user's language, you can parse it from Date
's string representation like so:
function getTimezoneName() {_x000D_
const today = new Date();_x000D_
const short = today.toLocaleDateString(undefined);_x000D_
const full = today.toLocaleDateString(undefined, { timeZoneName: 'long' });_x000D_
_x000D_
// Trying to remove date from the string in a locale-agnostic way_x000D_
const shortIndex = full.indexOf(short);_x000D_
if (shortIndex >= 0) {_x000D_
const trimmed = full.substring(0, shortIndex) + full.substring(shortIndex + short.length);_x000D_
_x000D_
// by this time `trimmed` should be the timezone's name with some punctuation -_x000D_
// trim it from both sides_x000D_
return trimmed.replace(/^[\s,.\-:;]+|[\s,.\-:;]+$/g, '');_x000D_
_x000D_
} else {_x000D_
// in some magic case when short representation of date is not present in the long one, just return the long one as a fallback, since it should contain the timezone's name_x000D_
return full;_x000D_
}_x000D_
}_x000D_
_x000D_
console.log(getTimezoneName());
_x000D_
Tested in Chrome and Firefox.
Ofcourse, this will not work as intended in some of the environments. For example, node.js returns a GMT offset (e.g. GMT+07:00
) instead of a name. But I think it's still readable as a fallback.
P.S. Won't work in IE11, just as the Intl...
solution.
mythreads = threading.enumerate()
Enumerate returns a list of all Thread objects still alive. https://docs.python.org/3.6/library/threading.html
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
The official RFC which defines this specification could be found here:
http://tools.ietf.org/html/rfc4021#section-2.1.2 (look at paragraph 2.1.2. and the following)
2.1.2. Header Field: From
Description: Mailbox of message author [...] Related information: Specifies the author(s) of the message; that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. Defined as standard by RFC 822.
2.1.3. Header Field: Sender
Description: Mailbox of message sender [...] Related information: Specifies the mailbox of the agent responsible for the actual transmission of the message. Defined as standard by RFC 822.
2.1.22. Header Field: Return-Path
Description: Message return path [...] Related information: Return path for message response diagnostics. See also RFC 2821 [17]. Defined as standard by RFC 822.
In case that you have Ubuntu in your machine, the following steps will help you:
Open your terminal and paste: sudo apt-get install php-soap.
Restart your apache2 server in terminal : service apache2 restart.
To check use your php test file again to be seems like mine in step 1.
Only the "Continue For" is an acceptable standard (the rest leads to "spaghetti code").
At least with "continue for" the programmer knows the code goes directly to the top of the loop.
For purists though, something like this is best since it is pure "non-spaghetti" code.
Dim bKeepGoing as Boolean
For Each I As Item In Items
bKeepGoing = True
If I = x Then
bKeepGoing = False
End If
if bKeepGoing then
' Do something
endif
Next
For ease of coding though, "Continue For" is OK. (Good idea to comment it though).
Using "Continue For"
For Each I As Item In Items
If I = x Then
Continue For 'skip back directly to top of loop
End If
' Do something
Next
$dbc
is returning false. Your query has an error in it:
SELECT users.*, profile.* --You do not join with profile anywhere.
FROM users
INNER JOIN contact_info
ON contact_info.user_id = users.user_id
WHERE users.user_id=3");
The fix for this in general has been described by Raveren.
I've got that problem because of some internall error in Android plugin. When I've tried to open some layout xml, I've got error:
The project target (Android 2.2) was not properly loaded.
Fortunatelly in my case restarting Eclipse and cleaning the project helped.
Note: I don't know the correct answer, but the below is just my personal speculation!
As has been mentioned a 0 before a number means it's octal:
04524 // octal, leading 0
Imagine needing to come up with a system to denote hexadecimal numbers, and note we're working in a C style environment. How about ending with h like assembly? Unfortunately you can't - it would allow you to make tokens which are valid identifiers (eg. you could name a variable the same thing) which would make for some nasty ambiguities.
8000h // hex
FF00h // oops - valid identifier! Hex or a variable or type named FF00h?
You can't lead with a character for the same reason:
xFF00 // also valid identifier
Using a hash was probably thrown out because it conflicts with the preprocessor:
#define ...
#FF00 // invalid preprocessor token?
In the end, for whatever reason, they decided to put an x after a leading 0 to denote hexadecimal. It is unambiguous since it still starts with a number character so can't be a valid identifier, and is probably based off the octal convention of a leading 0.
0xFF00 // definitely not an identifier!
I added file called .prettierrc
in my project folder.
File content:
{
"singleQuote": true,
"vetur.format.defaultFormatterOptions": {
"prettier": {
"singleQuote": true
}
}
}
select#xyz {
border:0px;
outline:0px;
}
Exact solution.
You can use an IF to test:
check:
@[ "${var}" ] || ( echo ">> var is not set"; exit 1 )
Result:
$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1
I just managed to wedge myself pretty thoroughly trying to follow user619330's advice above. The situation was: (1): I had added some files while working on my initial branch, branch1; (2) I created a new branch, branch2 for further development, branching it off from the trunk and then merging in my changes from branch1 (3) A co-worker had copied my mods from branch1 to his own branch, added further mods, and then merged back to the trunk; (4) I now wanted to merge the latest changes from trunk into my current working branch, branch2. This is with svn 1.6.17.
The merge had tree conflicts with the new files, and I wanted the new version from the trunk where they differed, so from a clean copy of branch2, I did an svn delete of the conflicting files, committed these branch2 changes (thus creating a temporary version of branch2 without the files in question), and then did my merge from the trunk. I did this because I wanted the history to match the trunk version so that I wouldn't have more problems later when trying to merge back to trunk. Merge went fine, I got the trunk version of the files, svn st shows all ok, and then I hit more tree conflicts while trying to commit the changes, between the delete I had done earlier and the add from the merge. Did an svn resolve of the conflicts in favor of my working copy (which now had the trunk version of the files), and got it to commit. All should be good, right?
Well, no. An update of another copy of branch2 resulted in the old version of the files (pre-trunk merge). So now I have two different working copies of branch2, supposedly updated to the same version, with two different versions of the files, and both insisting that they are fully up to date! Checking out a clean copy of branch2 resulted in the old (pre-trunk) version of the files. I manually update these to the trunk version and commit the changes, go back to my first working copy (from which I had submitted the trunk changes originally), try to update it, and now get a checksum error on the files in question. Blow the directory in question away, get a new version via update, and finally I have what should be a good version of branch2 with the trunk changes. I hope. Caveat developer.
<div>
tags are always abused to create a web layout. Its symbolic purpose is to divide a section/portion in the page so that separate style can be added or applied to it. [w3schools Doc] [W3C]
some
and another
has.HTML5, has more logical meaning tags, instead of having plain layout tags. The section
, header
, nav
, aside
everything have their own semantic meaning to it. And are used against <div>
On virtual hosting check your disk quota
.
if quota exceed, move_uploaded_file
return error.
PS : I've been looking for this for a long time :)
I'm using NetBeans and needed a solution for this also. After googleling around and starting from Christopher's answer i managed to build a script that helps you easily do this in NetBeans. I'm putting the instructions here in case someone else will need them.
What you have to do is download one-jar. You can use the link from here: http://one-jar.sourceforge.net/index.php?page=getting-started&file=ant Extract the jar archive and look for one-jar\dist folder that contains one-jar-ant-task-.jar, one-jar-ant-task.xml and one-jar-boot-.jar. Extract them or copy them to a path that we will add to the script below, as the value of the property one-jar.dist.dir.
Just copy the following script at the end of your build.xml script (from your NetBeans project), just before /project tag, replace the value for one-jar.dist.dir with the correct path and run one-jar target.
For those of you that are unfamiliar with running targets, this tutorial might help: http://www.oracle.com/technetwork/articles/javase/index-139904.html . It also shows you how to place sources into one jar, but they are exploded, not compressed into jars.
<property name="one-jar.dist.dir" value="path\to\one-jar-ant"/>
<import file="${one-jar.dist.dir}/one-jar-ant-task.xml" optional="true" />
<target name="one-jar" depends="jar">
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<property name="src.dir" value="src"/>
<property name="bin.dir" value="bin"/>
<property name="build.dir" value="build"/>
<property name="dist.dir" value="dist"/>
<property name="external.lib.dir" value="${dist.dir}/lib"/>
<property name="classes.dir" value="${build.dir}/classes"/>
<property name="jar.target.dir" value="${build.dir}/jars"/>
<property name="final.jar" value="${dist.dir}/${ant.project.name}.jar"/>
<property name="main.class" value="${main.class}"/>
<path id="project.classpath">
<fileset dir="${external.lib.dir}">
<include name="*.jar"/>
</fileset>
</path>
<mkdir dir="${bin.dir}"/>
<!-- <mkdir dir="${build.dir}"/> -->
<!-- <mkdir dir="${classes.dir}"/> -->
<mkdir dir="${jar.target.dir}"/>
<copy includeemptydirs="false" todir="${classes.dir}">
<fileset dir="${src.dir}">
<exclude name="**/*.launch"/>
<exclude name="**/*.java"/>
</fileset>
</copy>
<!-- <echo message="${ant.project.name}: ${ant.file}"/> -->
<javac debug="true" debuglevel="${debuglevel}" destdir="${classes.dir}" source="${source}" target="${target}">
<src path="${src.dir}"/>
<classpath refid="project.classpath"/>
</javac>
<delete file="${final.jar}" />
<one-jar destfile="${final.jar}" onejarmainclass="${main.class}">
<main>
<fileset dir="${classes.dir}"/>
</main>
<lib>
<fileset dir="${external.lib.dir}" />
</lib>
</one-jar>
<delete dir="${jar.target.dir}"/>
<delete dir="${bin.dir}"/>
<delete dir="${external.lib.dir}"/>
</target>
Best of luck and don't forget to vote up if it helped you.
giving a form element a name of submit will simple shadow the submit property . make sure you don't have a form element with the name submit and you should be able to access the submit function just fine .
<select>
<option value="" disabled selected hidden>Select an Option</option>
<option value="one">Option 1</option>
<option value="two">Option 2</option>
</select>
IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.
Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.
SELECT *
FROM my_table
WHERE substr(my_field,1,5) = "abcde";
Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;
).
Query string appears after the path (if any) and starts with a question mark character (?
).
Both parameters and query string contain key-value pairs.
In a GET
request, parameters appear in the URL itself:
<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>
In a POST
request, parameters can appear in the URL itself, but also in the datastream (as known as content).
Query string is always a part of the URL.
Parameters can be buried in form-data
datastream when using POST method so they may not appear in the URL. Yes a POST
request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.
I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST
request, or even let the code handling a GET
request share some parts with the code handling a POST
. Of course this can work only with server code supporting parameters in a URL.
Until you get better insights, I suggest you to use parameters only in form-data
datastream of POST
requests.
Sources:
put this in your php page.
ini_set("error_reporting", E_ALL & ~E_DEPRECATED);
Let's me give a more detail example. As to the below struct:
struct Count{
uint32_t c;
Count(uint32_t i=0):c(i){}
uint32_t getCount(){
return c;
}
uint32_t add(const Count& count){
uint32_t total = c + count.getCount();
return total;
}
};
As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object
. In the method add
count
is declared as const object, but the method getCount
is not const method, so count.getCount()
may change the members in count
.
Compile error as below(core message in my compiler):
error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]
To solve the above problem, you can:
uint32_t getCount(){...}
to uint32_t getCount() const {...}
. So count.getCount()
won't change the members in count
.or
uint32_t add(const Count& count){...}
to uint32_t add(Count& count){...}
. So count
don't care about changing members in it.As to you problem, objects in the std::set are stored as const StudentT, but the method getId
and getName
are not const, so you give the above error.
You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.
The following should work:
public static void main(String[] args)
{
final String title = "Test Window";
final int width = 1200;
final int height = width / 16 * 9;
//Creating the frame.
JFrame frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
//Creating the canvas.
Canvas canvas = new Canvas();
canvas.setSize(width, height);
canvas.setBackground(Color.BLACK);
canvas.setVisible(true);
canvas.setFocusable(false);
//Putting it all together.
frame.add(canvas);
canvas.createBufferStrategy(3);
boolean running = true;
BufferStrategy bufferStrategy;
Graphics graphics;
while (running) {
bufferStrategy = canvas.getBufferStrategy();
graphics = bufferStrategy.getDrawGraphics();
graphics.clearRect(0, 0, width, height);
graphics.setColor(Color.GREEN);
graphics.drawString("This is some text placed in the top left corner.", 5, 15);
bufferStrategy.show();
graphics.dispose();
}
}
Just to complement the accepted answer, you could also use System.out.read()
like this:
class Example {
public static void main(String args[])
throws java.io.IOException { // This works! No need to use try{// ...}catch(IOException ex){// ...}
System.out.println("Type a letter: ");
char letter = (char) System.in.read();
System.out.println("You typed the letter " + letter);
}
}
So many ways to skin this cat. You can do this in a closure. This code will give you a read-only , namespaced way to have constants. Just declare them in the Public area.
//Namespaced Constants
var MyAppName;
//MyAppName Namespace
(function (MyAppName) {
//MyAppName.Constants Namespace
(function (Constants) {
//Private
function createConstant(name, val) {
Object.defineProperty(MyAppName.Constants, name, {
value: val,
writable: false
});
}
//Public
Constants.FOO = createConstant("FOO", 1);
Constants.FOO2 = createConstant("FOO2", 1);
MyAppName.Constants = Constants;
})(MyAppName.Constants || (MyAppName.Constants = {}));
})(MyAppName || (MyAppName = {}));
Usage:
console.log(MyAppName.Constants.FOO); //prints 1
MyAppName.Constants.FOO = 2;
console.log(MyAppName.Constants.FOO); //does not change - still prints 1
From android 6.0 you need to check for user permission, if you want to use GoogleMap.setMyLocationEnabled(true)
you will get Call requires permission which may be rejected by user
error
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
if you want to read more, check google map docs
SSIS (SQL Server Integration Services) is an upgrade of DTS (Data Transformation Services), which is a feature of the previous version of SQL Server. SSIS packages can be created in BIDS (Business Intelligence Development Studio). These can be used to merge data from heterogeneous data sources into SQL Server. They can also be used to populate data warehouses, to clean and standardize data, and to automate administrative tasks.
SQL Server Integration Services (SSIS) is a component of Microsoft SQL Server 2005. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is only available in the "Standard" and "Enterprise" editions. Integration Services provides a platform to build data integration and workflow applications. The primary use for SSIS is data warehousing as the product features a fast and flexible tool for data extraction, transformation, and loading (ETL).). The tool may also be used to automate maintenance of SQL Server databases, update multidimensional cube data, and perform other functions.
Try jQuery animate()
method, ex.
$("#divid").animate({'width':perc+'%'});
Assuming you're in control of the pattern used to find test classes, I'd suggest changing it to match *Test
rather than *Test*
. That way TestHelper
won't get matched, but FooTest
will.
You need to use to_timestamp()
to convert your string to a proper timestamp
value:
to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
If your column is of type DATE
(which also supports seconds), you need to use to_date()
to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
To get this into a where
condition use the following:
select *
from TableA
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')
You never need to use to_timestamp()
on a column that is of type timestamp
.
To translate your *nix style command script to windows/command batch style it would go like this:
SET PROJ_HOME=%USERPROFILE%/proj/111
SET PROJECT_BASEDIR=%PROJ_HOME%/exercises/ex1
mkdir "%PROJ_HOME%"
mkdir on windows doens't have a -p parameter : from the MKDIR /? help:
MKDIR creates any intermediate directories in the path, if needed.
which basically is what mkdir -p (or --parents for purists) on *nix does, as taken from the man guide
Having the same issue here. As pointed out by @Izabela Orlowska, this problem is most likely caused by special characters in path (android grandle files, resources etc..).
For me: having rí
in folder name caused all the problems. Make sure you do not have any special characters in paths. Disabling AAPT2 is only a temporary "solution". Your project path contains non-ASCII characters android studio
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString()
and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
Put this in your activity declaration in manifest file
<activity android:windowSoftInputMode="adjustPan|adjustResize"> </activity>
or if you want you can add in onCreate() method of your activity
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
There are (more than) three popular ways to use MySQL from PHP. This outlines some features/differences PHP: Choosing an API:
I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.
android:onClick
is for API level 4 onwards, so if you're targeting < 1.6, then you can't use it.
Select first the text you want to format and then press Ctrl+I.
Use Cmd+A first if you wish to format all text in the selected file.
Note: this procedure only re-indents the lines, it does not do any advanced formatting.
The new key binding to re-indent is control+I.
By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:
myList.getSelectedItem();
The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:
myList.getItemAtPosition(position);
A much easier way to do this is using PowerShell, like so:
Get-Website yoursite | % { Join-Path ($_.logFile.Directory -replace '%SystemDrive%', $env:SystemDrive) "W3SVC$($_.id)" }
or simply
Get-Website yoursite | % { $_.logFile.Directory, $_.id }
if you just need the info for yourself and don't mind parsing the result in your brain :).
For bonus points, append | ii
to the first command to open in Explorer, or | gci
to list the contents of the folder.
I use your exact proposed code with only some few additional lines. The idea is more or less the same of the one proposed by @elias, but in this solution there cannot be conflicts on the keys since each file in the directory has a different filename and so adding it to the key solves the conflicts. The first part of the key is the datetime string formatted in a manner such that I can lexicographically compare two of them.
if ($handle = opendir('.')) {
$result = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$lastModified = date('F d Y, H:i:s',filemtime($file));
if(strlen($file)-strpos($file,".swf")== 4){
$result [date('Y-m-d H:i:s',filemtime($file)).$file] =
"<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
}
}
}
closedir($handle);
krsort($result);
echo implode('', $result);
}
Best solution: Don't use global
s
>>> test1 = 0
>>> def test_func(x):
return x + 1
>>> test1 = test_func(test1)
>>> test1
1
Use git clean
Get help on this running
git clean -h
If you want to see what would happen first, make sure to pass the -n switch for a dry run:
git clean -xn
To remove gitingnored garbage
git clean -xdf
Careful: You may be ignoring local config files like database.yml which would also be removed. Use at your own risk.
Then
git add .
git commit -m ".gitignore is now working"
git push
BeautifulSoup(text, features="html.parser").text
For the people who were seeking deep info in my answer, sorry.
I'll explain it.
Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.
The above like just take all the HTML text (text
) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)
Once done so, we just request all the text from within the HTML object.
If you scale 1600x900
to 1280x720
you have
scale_x = 1280.0/1600
scale_y = 720.0/900
Then you can use it to find button size, and button position
button_width = 300 * scale_x
button_height = 300 * scale_y
button_x = 1440 * scale_x
button_y = 860 * scale_y
If you scale 1280x720
to 1600x900
you have
scale_x = 1600.0/1280
scale_y = 900.0/720
and rest is the same.
I add .0
to value to make float
- otherwise scale_x
, scale_y
will be rounded to integer
- in this example to 0
(zero) (Python 2.x)
You might want to modify your jQuery code a bit to '#demolist li a'
so it specifically selects the text that is in the link rather than the text that is in the li element. That would allow you to have a sub-menu without causing issues. Also since your are specifically selecting the a tag you can access it with $(this).text();
.
$('#datebox li a').on('click', function(){
//$('#datebox').val($(this).text());
alert($(this).text());
});
An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files.
AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.
It is working. Just modify to null check:
if(document.body != null){
document.body.appendChild(element);
}
Pointy's suggestion is good; it may work, but I didn't try.
%g can do this:
#include <stdio.h>
int main() {
float w = 234.567;
char x[__SIZEOF_FLOAT__];
sprintf(x, "%g", w);
puts(x);
}
You can use an overlay with opacity set in order to the buttons/anchors in the back stay visible, but once you have that overlay over an element, you can't click it.
First backup the database. Then drop any foreign key associated with the table. truncate the foreign key table.Truncate the current table. Remove the required primary keys. Use sqlyog or workbench or heidisql or dbeaver or phpmyadmin.
You can get the desired result with the code below. Two'H' in HH
is for 24-hour format.
return fechaHora.Value.ToString("HH:mm");
Great native python based answers given by other users. But here's the nltk
approach (just in case, the OP gets penalized for reinventing what's already existing in the nltk
library).
There is an ngram module that people seldom use in nltk
. It's not because it's hard to read ngrams, but training a model base on ngrams where n > 3 will result in much data sparsity.
from nltk import ngrams
sentence = 'this is a foo bar sentences and i want to ngramize it'
n = 6
sixgrams = ngrams(sentence.split(), n)
for grams in sixgrams:
print grams
In case you don't have permission to 'Modify', you can install a free tool called "SQL Search" (by Redgate). I use it to search for keywords that I know will be in the SP and it returns a preview of the SP code with the keywords highlighted.
Ingenious! I then copy this code into my own SP.
Basically the difference between them are performance characteristics and blocking behavior.
Taking the easiest first, ArrayBlockingQueue
is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.
The most important difference between LinkedBlockingQueue
and ConcurrentLinkedQueue
is that if you request an element from a LinkedBlockingQueue
and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue
will return right away with the behavior of an empty queue.
Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.
Laravel now supports this feature out-of-the-box! (I believe since 5.5 or earlier).
Add a __construct()
method to your Controller
as shown below:
public function __construct()
{
$this->middleware('auth');
}
After login, your users will then be redirected to the page they intended to visit initially.
You can also add Laravel's email verification feature as required by your application logic:
public function __construct()
{
$this->middleware(['auth', 'verified']);
}
The documentation contains a very brief example:
It's also possible to choose which controller's methods the middleware applies to by using except
or only
options.
Example with except
:
public function __construct()
{
$this->middleware('auth', ['except' => ['index', 'show']]);
}
Example with only
:
public function __construct()
{
$this->middleware('auth', ['only' => ['index', 'show']]);
}
More information about except
and only
middleware options:
No need to hack settings. There is a simple way:
print(df.to_string())
I think there is only one intuitive solution and it is:
int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);
Output:
First: 1
Last: 5
If you're not only seeking for a number but also hex or uuid it's worth mentioning that the SecureRandom
module found its way from ActiveSupport
to the ruby core in 1.9.2+. So without the need for a full blown framework:
require 'securerandom'
p SecureRandom.random_number(100) #=> 15
p SecureRandom.random_number(100) #=> 88
p SecureRandom.random_number #=> 0.596506046187744
p SecureRandom.random_number #=> 0.350621695741409
p SecureRandom.hex #=> "eb693ec8252cd630102fd0d0fb7c3485"
It's documented here: Ruby 1.9.3 - Module: SecureRandom (lib/securerandom.rb)
There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.
When you do something like git add file
you add it to the index. And when you commit it, you add it to the tree as well.
It will probably help you to know the three more common flags in git reset
:
git reset [--
<mode>
] [<commit>
]This form resets the current branch head to
<commit>
and possibly updates the index (resetting it to the tree of<commit>
) and the working tree depending on<mode>
, which must be one of the following:
--softDoes not touch the index file nor the working tree at all (but resets the head to
<commit>
, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.--mixed
Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.
--hard
Resets the index and working tree. Any changes to tracked files in the working tree since
<commit>
are discarded.
Now, when you do something like git reset HEAD
, what you are actually doing is git reset HEAD --mixed
and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add
). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add
was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD
is the exact opposite of git add
.
git rm
, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached
, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add
was used to add a new (previously untracked) file, then git rm --cached
is the exact opposite of git add
(and is pretty much identical to git reset HEAD
).
Git 2.25 introduced a new command for these cases, git restore
, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.
I think someone should face the same problem that can't find out the branch, although it actually exists in one branch.
You'd better pull all first:
git pull --all
Then do the branch search:
git name-rev <SHA>
or:
git branch --contains <SHA>
Might be a very late answer, but this is good and simple.
select * from table_name order by id desc limit 5
This query will return a set of last 5 values(last 5 rows) you 've inserted in your table
You can have multiple projects in one instance of Visual Studio. The point of a VS solution is to bring together all the projects you want to work with in one place, so you can't have multiple solutions in one instance. You'd have to open each solution separately.
Here is something else interesting you can do. Define a function to call just before each ajax call. Also assign a function to call after each ajax call is complete. The first function will set the wait cursor and the second will clear it. They look like the following:
$(document).ajaxComplete(function(event, request, settings) {
$('*').css('cursor', 'default');
});
function waitCursor() {
$('*').css('cursor', 'progress');
}
try to use
<?php require_once($_SERVER['DOCUMENT_ROOT'].'/web/a.php'); ?>
Check this basic code to setup html server. its work for me.
var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(8000); });
For me, this turned out to be an unimplemented parcelable class with no datatype [Any]; due to which there was a TODO() constructor created in parcelable implementation of model class.
Hope it helps someone.
@SerializedName("firstTxnDetails")
var firstTxnDetails: Any? = Any()
//in parcelable implementation :
constructor(parcel: Parcel) : this(
parcel.readInt(),
parcel.readLong(),
parcel.readInt(),
parcel.readDouble(),
parcel.readLong(),
TODO("firstTxnDetails"), // -> correct this
parcel.readString(),
parcel.readLong(),
parcel.readParcelable(MasterSavingPlan::class.java.classLoader),
parcel.readInt(),
parcel.readString(),
parcel.readString()) {
}
When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.
With Basic Auth, the HTTP request from the question will look something like this:
GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk
The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password)
.
To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl
, the username and password will be clearly visible on the process list and might turn up in the bash history file.
When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.
Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.
When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.
Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.
The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.
This is more or less what it should look like (no libcurl available here to test)
#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>
size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int main(void) {
CURL *curl;
FILE *fp;
CURLcode res;
char *url = "http://localhost/aaa.txt";
char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
res = curl_easy_perform(curl);
/* always cleanup */
curl_easy_cleanup(curl);
fclose(fp);
}
return 0;
}
Updated: as suggested by @rsethc types.h
and easy.h
aren't present in current cURL versions anymore.
You'll find the answer to your question in the help page for ?axis
.
Here is one of the help page examples, modified with your data:
Option 1: use xaxp
to define the axis labels
plot(x,y, xaxt="n")
axis(1, xaxp=c(10, 200, 19), las=2)
Option 2: Use at
and seq()
to define the labels:
plot(x,y, xaxt="n")
axis(1, at = seq(10, 200, by = 10), las=2)
Both these options yield the same graphic:
PS. Since you have a large number of labels, you'll have to use additional arguments to get the text to fit in the plot. I use las
to rotate the labels.
You can use the Path
api:
Path p = Paths.get(yourFileNameUri);
Path folder = p.getParent();
I didn't see the link here, but there's a beta .NET Connector for MySql. Click "Development Releases" to download 6.3.2 beta, which has EF4/VS2010 integration:
http://dev.mysql.com/downloads/connector/net/5.0.html#downloads
Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.
This jQuery filter will remove the class "highlightCriteria" only for the input or select fields that have this class.
$form.find('input,select').filter(function () {
if((!!this.value) && (!!this.name)) {
$("#"+this.id).removeClass("highlightCriteria");
}
});
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
Yes the restOfTheUrl
is not returning only required value but we can get the value by using UriTemplate
matching.
I have solved the problem, so here the working solution for the problem:
@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
String restOfTheUrl = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
/*We can use UriTemplate to map the restOfTheUrl*/
UriTemplate template = new UriTemplate("/{id}/{value}");
boolean isTemplateMatched = template.matches(restOfTheUrl);
if(isTemplateMatched) {
Map<String, String> matchTemplate = new HashMap<String, String>();
matchTemplate = template.match(restOfTheUrl);
String value = matchTemplate.get("value");
/*variable `value` will contain the required detail.*/
}
}
You can create a .a
file using the ar
utility, like so:
ar crf lib/libHeader.a header.o
lib
is a directory that contains all your libraries. it is good practice to organise your code this way and separate the code and the object files. Having everything in one directory generally looks ugly. The above line creates libHeader.a
in the directory lib
. So, in your current directory, do:
mkdir lib
Then run the above ar
command.
When linking all libraries, you can do it like so:
g++ test.o -L./lib -lHeader -o test
The -L
flag will get g++
to add the lib/
directory to the path. This way, g++
knows what directory to search when looking for libHeader
. -llibHeader
flags the specific library to link.
where test.o is created like so:
g++ -c test.cpp -o test.o
I encountered this problem while executing the "npm publish" command.
Then I checked the error log, and solved this by executing "npm config set registry http://registry.npmjs.org" command. The obvious reason for this problem is that I set up another registry.
So, if you are in the same situation as mine, try setting the registry to official one.
With python 3.6+:
msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"
You can use location
to send state to other component, like this
In your Source Component
this.props.history.push(pathComponent, sendState);
pathComponent
is target component that will receive the state
In your Target Component you can receive the state like this if your use class component
constructor(props) {
this.state = this.props.location.state
}
constructor(props: {}) {
const receiveState = this.props.location.state as StateType // you must parse into your state interface or type
this.state = receiveState
}
If you want to reset the received state. Use history
to replace the location, like this
this.props.history({pathName: currentPath, state: resetState})
currentPath
is the Target Component path
resetState
is new value state whatever you want
FileReader reads from files on the file system.
Perhaps you intended to use something like this to load a file from the class path
// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
.getResourceAsStream("config.txt");
Or you could extract the file from the jar before reading it.
setInterval
or setTimeout
You should pass a reference to a function as the first argument for setTimeout
or setInterval
. This reference may be in the form of:
An anonymous function
setTimeout(function(){/* Look mah! No name! */},2000);
A name of an existing function
function foo(){...}
setTimeout(foo, 2000);
A variable that points to an existing function
var foo = function(){...};
setTimeout(foo, 2000);
Do note that I set "variable in a function" separately from "function name". It's not apparent that variables and function names occupy the same namespace and can clobber each other.
To call a function and pass parameters, you can call the function inside the callback assigned to the timer:
setTimeout(function(){
foo(arg1, arg2, ...argN);
}, 1000);
There is another method to pass in arguments into the handler, however it's not cross-browser compatible.
setTimeout(foo, 2000, arg1, arg2, ...argN);
By default, the context of the callback (the value of this
inside the function called by the timer) when executed is the global object window
. Should you want to change it, use bind
.
setTimeout(function(){
this === YOUR_CONTEXT; // true
}.bind(YOUR_CONTEXT), 2000);
Although it's possible, you should not pass a string to setTimeout
or setInterval
. Passing a string makes setTimeout()
or setInterval()
use a functionality similar to eval()
that executes strings as scripts, making arbitrary and potentially harmful script execution possible.
Here's a trick that worked for me:
handleClick = e => {
if (e.target === e.currentTarget) {
// do something
} else {
// do something else
}
}
Explanation: I attached handleClick
to a backdrop of a modal window, but it also fired on every click inside of a modal window (because it was IN the backdrop div). So I added the condition (e.target === e.currentTarget)
, which is only fulfilled when a backdrop is clicked.
with this simple code you can do that:
let el = $('<div></div>');
$(document.body).append(el);
el.html(`<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>`);
console.log(el.find('a[href="test0"]'));
Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviours after this
NotificationManager notificationManager =
getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
IList<string> list = new List<string> {"test1", "test2", "test3"}
I show you this with an example:
string userName= textBox1.text;
and then use it as you wish
$fname = "database.php";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("192.168.1.198", "localhost", $content);
$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
One more option is to add the path of the privatekey file like this in terminal:
ssh-add "path to the privatekeyfile"
and then execute the pull command
it also can be a great idea using concat for EL + MAP + JSON problem like in this example :
#{myMap[''.concat(myid)].content}
$ lsof -wni tcp:3000
# Kill the running process
$ kill -9 5946
$ rm tmp/server.pids
foreman start etc start the service
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
Thanks for the advice. As there is no equivalent in SQL server. I simply created a 2nd field which converted the TimeSpan to ticks and stored that in the DB. I then prevented storing the TimeSpan
public Int64 ValidityPeriodTicks { get; set; }
[NotMapped]
public TimeSpan ValidityPeriod
{
get { return TimeSpan.FromTicks(ValidityPeriodTicks); }
set { ValidityPeriodTicks = value.Ticks; }
}
Something very similar can be seen on http://goo.gl when you shorten the URL.
There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.
When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)
When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.
So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.
Found testing for window.Touch didn't work on android but this does:
function is_touch_device() {
return !!('ontouchstart' in window);
}
See article: What's the best way to detect a 'touch screen' device using JavaScript?
.e:hover{
background-color:#FF0000;
}
You have to explicitly define the constructor in B and explicitly call the constructor for the parent.
B(int x) : A(x) { }
or
B() : A(5) { }
This works fine for me:
<style type="text/css">_x000D_
#table {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
}_x000D_
</style>
_x000D_
For me, just changing Height and Width to 100% doesn’t do it for me, and neither do setting left, right, top and bottom to 0, but using them both together will do the trick.
For Windows 10 x64
and Python
:
Open a Visual Studio x64 command prompt, and use dumpbin:
dumpbin /dependents [Python Module DLL or PYD file]
If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.
Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.
I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.
It was giving this error: ImportError: DLL load failed: The specified module could not be found
Opened a Visual Studio x64 command prompt.
Under Windows, a .pyd
file is a .dll
file in disguise, so we want to run dumpbin on this file.
cd MyLibrary\build\lib.win-amd64-3.7\Debug
dumpbin /dependents MyLibrary.cp37-win_amd64.pyd
which prints this:
Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file MyLibrary.cp37-win_amd64.pyd
File Type: DLL
Image has the following dependencies:
clang_rt.asan_dbg_dynamic-x86_64.dll
gtestd.dll
tbb_debug.dll
python37.dll
KERNEL32.dll
MSVCP140D.dll
VCOMP140D.DLL
VCRUNTIME140D.dll
VCRUNTIME140_1D.dll
ucrtbased.dll
Summary
1000 .00cfg
D6000 .data
7000 .idata
46000 .pdata
341000 .rdata
23000 .reloc
1000 .rsrc
856000 .text
Searched for clang_rt.asan_dbg_dynamic-x86_64.dll
, copied it into the same directory, problem solved.
Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.
Please feel free to add your own case studies here! I've made it a community wiki answer.
My solution is similar to Payam's, except I am using
//older code
//postman.setGlobalVariable("currentDate", new Date().toLocaleDateString());
pm.globals.set("currentDate", new Date().toLocaleDateString());
If you hit the "3 dots" on the folder and click "Edit"
Then set Pre-Request Scripts for the all calls, so the global variable is always available.
The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.
The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.
I solved this problem like this.
UIImageView
(with UIViewContentModeScaleAspectFit
)(CGSize imageSize = imageView.image.size)
UIImageView
resize. [imageView sizeThatFits:imageSize]
I wanted to put UIView on the top center of UICollectionViewCell
.
so, I used this function.
- (void)setImageToCenter:(UIImageView *)imageView
{
CGSize imageSize = imageView.image.size;
[imageView sizeThatFits:imageSize];
CGPoint imageViewCenter = imageView.center;
imageViewCenter.x = CGRectGetMidX(self.contentView.frame);
[imageView setCenter:imageViewCenter];
}
It works for me.
Actually xcopy does not ask you if the original file exists, but if you want to put it in a new folder named Shapes.atc, or in the folder Support (which is what you want.
To prevent xcopy from asking this, just tell him the destination folder, so there's no ambiguity:
xcopy /s/y "J:\Old path\Shapes.atc" "C:\Documents and Settings\his name\Support"
If you want to change the filename in destination just use copy (which is more adapted than xcopy when copying files):
copy /y "J:\Old path\Shapes.atc" "C:\Documents and Settings\his name\Support\Shapes-new.atc
I'm not sure if this is helping you, but I guess that when you do a svn add mysql
after you've deleted it it will just reinstantiate the directory (so don't do a mkdir yourself). If you create a directory yourself svn expects a .svn directory inside it because it already 'knows' about it.
It's just the method. You're not missing anything. The official documentation shows that you can use list unpacking to supply several paths:
s = "c:/,home,foo,bar,some.txt".split(",")
os.path.join(*s)
Note the *s
intead of just s
in os.path.join(*s)
. Using the asterisk will trigger the unpacking of the list, which means that each list argument will be supplied to the function as a separate argument.
On the server, try:
netstat -an
and look to see if tcp port 22
is opened (use findstr
in Windows or grep
in Unix).