If you you want to copy a sub-set of the source table you can do:
INSERT INTO def (field_1, field_2, field3)
SELECT other_field_1, other_field_2, other_field_3 from `abc`
or to copy ALL fields from the source table to destination table you can do more simply:
INSERT INTO def
SELECT * from `abc`
Multiple SQL statements must be executed with the mysqli_multi_query()
function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
In SQL or MySQL you can use the char
or chr
functions to enter in an ASCII 13 for carriage return line feed, the \n
equivilent. But as @David M has stated, you are most likely looking to have the HTML show this break and a br is what will work.
You can expend the following function in order to pull out more parameters from the DB before the insert:
--
-- insert_employee (Function)
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2)
RETURN VARCHAR2 AS
p_state_id varchar2(30) := '';
BEGIN
select state_id
into p_state_id
from states where lower(emp_state) = state_name;
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES
(p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);
return 'SUCCESS';
EXCEPTION
WHEN others THEN
RETURN 'FAIL';
END;
/
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
Addition to Mark Byers answer :
Sometimes you also want to insert Hardcoded details else there may be Unique constraint fail etc. So use following in such situation where you override some values of the columns.
INSERT INTO matrimony_domain_details (domain, type, logo_path)
SELECT 'www.example.com', type, logo_path
FROM matrimony_domain_details
WHERE id = 367
Here domain value is added by me me in Hardcoded way to get rid from Unique constraint.
I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)
public static bool IsStringType(object data)
{
return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
}
I was facing the same problem in IntelliJ. It was working from command line though.
I found the issue was because of an improper Gradle config in the IDE. I wasn't using the "default Gradle wrapper" as recommended:
sed -i '/^$/d' foo
This tells sed
to delete every line matching the regex ^$
i.e. every empty line. The -i
flag edits the file in-place, if your sed
doesn't support that you can write the output to a temporary file and replace the original:
sed '/^$/d' foo > foo.tmp
mv foo.tmp foo
If you also want to remove lines consisting only of whitespace (not just empty lines) then use:
sed -i '/^[[:space:]]*$/d' foo
Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:
sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo
You can also use 'name' instead of 'href' for a cleaner url:
$('a[name^=#]').click(function(){
var target = $(this).attr('name');
if (target == '#')
$('html, body').animate({scrollTop : 0}, 600);
else
$('html, body').animate({
scrollTop: $(target).offset().top - 100
}, 600);
});
Using Java 8
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Student {
String stud_id;
String stud_name;
String stud_location;
public String getStud_id() {
return stud_id;
}
public String getStud_name() {
return stud_name;
}
public String getStud_location() {
return stud_location;
}
Student(String sid, String sname, String slocation) {
this.stud_id = sid;
this.stud_name = sname;
this.stud_location = slocation;
}
}
class Temp
{
public static void main(String args[])
{
Stream<Student> studs =
Stream.of(new Student("1726", "John", "New York"),
new Student("4321", "Max", "California"),
new Student("2234", "Max", "Los Angeles"),
new Student("7765", "Sam", "California"));
Map<String, Map<Object, List<Student>>> map= studs.collect(Collectors.groupingBy(Student::getStud_name,Collectors.groupingBy(Student::getStud_location)));
System.out.println(map);//print by name and then location
}
}
The result will be:
{
Max={
Los Angeles=[Student@214c265e],
California=[Student@448139f0]
},
John={
New York=[Student@7cca494b]
},
Sam={
California=[Student@7ba4f24f]
}
}
According to this posting by the lead Jenkins developer, Kohsuke Kawaguchi, in 2009, there is no group support for the built-in Jenkins user database. Group support is only usable when integrating Jenkins with LDAP or Active Directory. This appears to be the same in 2012.
However, as Vadim wrote in his answer, you don't need group support for the built-in Jenkins user database, thanks to the Role strategy plug-in.
You could use os.listdir()
which returns a list of names (for both files and directories) in a given directory. If you need to distinguish between files and directories, call os.stat()
on each name.
Let me share the simple way to enable the remote debugging mode in tomcat7 with eclipse (Windows).
Step 1: open bin/startup.bat file
Step 2: add the below lines for debugging with JDPA option (it should starting line of the file )
set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
Step 3: in the same file .. go to end of the file modify this line -
call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%
instead of line
call "%EXECUTABLE%" start %CMD_LINE_ARGS%
step 4: then just run bin>startup.bat (so now your tomcat server ran in remote mode with port 8000).
step 5: after that lets connect your source project by eclipse IDE with remote client.
step6: In the Eclipse IDE go to "debug Configuration"
step7:click "remote java application" and on that click "New"
step8. in the "connect" tab set the parameter value
project= your source project
connection Type: standard (socket attached)
host: localhost
port:8000
step9: click apply and debug.
so finally your eclipse remote client is connected with the running tomcat server (debug mode).
Hope this approach might be help you.
Regards..
DATE(readingstamp) BETWEEN '2016-07-21' AND '2016-07-31' AND TIME(readingstamp) BETWEEN '08:00:00' AND '17:59:59'
simply separate the casting of date and time
I use:
ls -d */ | cut -f1 -d'/'
This creates a single column without a trailing slash - useful in scripts.
Remove star from COPY, with this Dockerfile:
FROM ubuntu
COPY files/ /files/
RUN ls -la /files/*
Structure is there:
$ docker build .
Sending build context to Docker daemon 5.632 kB
Sending build context to Docker daemon
Step 0 : FROM ubuntu
---> d0955f21bf24
Step 1 : COPY files/ /files/
---> 5cc4ae8708a6
Removing intermediate container c6f7f7ec8ccf
Step 2 : RUN ls -la /files/*
---> Running in 08ab9a1e042f
/files/folder1:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root 0 May 13 16:04 file1
-rw-r--r-- 1 root root 0 May 13 16:04 file2
/files/folder2:
total 8
drwxr-xr-x 2 root root 4096 May 13 16:04 .
drwxr-xr-x 4 root root 4096 May 13 16:05 ..
-rw-r--r-- 1 root root 0 May 13 16:04 file1
-rw-r--r-- 1 root root 0 May 13 16:04 file2
---> 03ff0a5d0e4b
Removing intermediate container 08ab9a1e042f
Successfully built 03ff0a5d0e4b
I just change the problem a little bit (map of strings) to show another interest of insert:
std::map<int, std::string> rancking;
rancking[0] = 42; // << some compilers [gcc] show no error
rancking.insert(std::pair<int, std::string>(0, 42));// always a compile error
the fact that compiler shows no error on "rancking[1] = 42;" can have devastating impact !
For me, this helped: 1. Configuration properties/General/Platform Toolset = Windows XP (V110_xp) 2. C/C++ Preprocessor definitions, add "WIN32" 3. Linker/System/Minimum required version = 5.01
We can use pytest-mock (https://pypi.org/project/pytest-mock/) mocker object to mock datetime behaviour in a particular module
Let's say you want to mock date time in the following file
# File path - source_dir/x/a.py
import datetime
def name_function():
name = datetime.now()
return f"name_{name}"
In the test function, mocker will be added to the function when test runs
def test_name_function(mocker):
mocker.patch('x.a.datetime')
x.a.datetime.now.return_value = datetime(2019, 1, 1)
actual = name_function()
assert actual == "name_2019-01-01"
Just use the existing method.. .ToList();
List<int> listArray = array.ToList();
KISS(KEEP IT SIMPLE SIR)
Leaving here a quick alternative, using class toggle on a table. The behavior is very similar than a select, but can be styled with transition, filters and colors, each children individually.
function toggleSelect(){ _x000D_
if (store.classList[0] === "hidden"){_x000D_
store.classList = "viewfull"_x000D_
}_x000D_
else {_x000D_
store.classList = "hidden"_x000D_
}_x000D_
}
_x000D_
#store {_x000D_
overflow-y: scroll;_x000D_
max-height: 110px;_x000D_
max-width: 50%_x000D_
}_x000D_
_x000D_
.hidden {_x000D_
display: none_x000D_
}_x000D_
_x000D_
.viewfull {_x000D_
display: block_x000D_
}_x000D_
_x000D_
#store :nth-child(4) {_x000D_
background-color: lime;_x000D_
}_x000D_
_x000D_
span {font-size:2rem;cursor:pointer}
_x000D_
<span onclick="toggleSelect()">?</span>_x000D_
<div id="store" class="hidden">_x000D_
_x000D_
<ul><li><a href="#keylogger">keylogger</a></li><li><a href="#1526269343113">1526269343113</a></li><li><a href="#slow">slow</a></li><li><a href="#slow2">slow2</a></li><li><a href="#Benchmark">Benchmark</a></li><li><a href="#modal">modal</a></li><li><a href="#buma">buma</a></li><li><a href="#1526099371108">1526099371108</a></li><a href="#1526099371108o">1526099371108o</a></li><li><a href="#pwnClrB">pwnClrB</a></li><li><a href="#stars%20u">stars%20u</a></li><li><a href="#pwnClrC">pwnClrC</a></li><li><a href="#stars ">stars </a></li><li><a href="#wello">wello</a></li><li><a href="#equalizer">equalizer</a></li><li><a href="#pwnClrA">pwnClrA</a></li></ul>_x000D_
_x000D_
</div>
_x000D_
@Column(nullable = false, updatable = false)
@CreationTimestamp
private Date created_at;
this worked for me. more info
The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
This works perfectly when used with onload as:
window.onload = function () {
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
console.log('Page load time is '+ loadTime);
}
Edit 1: Added some context to answer
Note: loadTime
is in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik
You can use:
for (int x = 0; x < 10; x++) {
if (x == 5) { // If x is 5, then break it.
break;
}
}
Try this:
for(String str: myList) {
if(str.trim().equals("A"))
return true;
}
return false;
You need to use str.equals
or str.equalsIgnoreCase
instead of contains
because contains
in string
works not the same as contains
in List
List<String> s = Arrays.asList("BAB", "SAB", "DAS");
s.contains("A"); // false
"BAB".contains("A"); // true
Check out std::stringstream
.
Sharing this as I've recently encountered issues similar to this thread
For a long time, my script worked well (basic payment form) and returned the POST variables to my success.php page and the IPN data as POST variables also. However, lately, I noticed the return page (success.php) was no longer receiving any POST vars. I tested in Sandbox and live and I'm pretty sure PayPal have changed something !
The notify_url still receives the correct IPN data allowing me to update DB, but I've not been able to display a success message on my return URL (success.php) page.
Despite trying many combinations to switch options on and off in PayPal website payment preferences and IPN, I've had to make some changes to my script to ensure I can still process a message. I've accomplished this by turning on PDT and Auto Return, after following this excellent guide.
Now it all works fine, but the only issue is the return URL contains all of the PDT variables which is ugly!
You may also find this helpful
If you use $(document).on()
to add a listener to a dynamically created element then you may have to use the following to remove it:
// add the listener
$(document).on('click','.element',function(){
// stuff
});
// remove the listener
$(document).off("click", ".element");
To link to a YouTube video so it plays in HD by default, use the following URL:
https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).
body
{
width:80%;
margin-left:auto;
margin-right:auto;
}
This will work on most browsers, including IE.
Question is good, but the answer is : it depends on that.
If the other webpage doesn't contain any form or text, for example you can use the CURL method to pickup the exact content and after then showing on your page. YOu can do it without using an iframe.
But, if the page what you want to embed contains for example a form it will not work correctly , because the form handling is on that site.
We can also make use of below given dependency and plugin in your pom file - I make use of maven. With the use of these you can generate POJO's as per your JSON Schema and then make use of code given below to populate request JSON object via src object specified as parameter to gson.toJson(Object src) or vice-versa. Look at the code below:
Gson gson = new GsonBuilder().create();
String payloadStr = gson.toJson(data.getMerchant().getStakeholder_list());
Gson gson2 = new Gson();
Error expectederr = gson2.fromJson(payloadStr, Error.class);
And the Maven settings:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>1.7.1</version>
</dependency>
<plugin>
<groupId>com.googlecode.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>0.3.7</version>
<configuration>
<sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
<targetPackage>com.example.types</targetPackage>
</configuration>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
There is much easier way:
props.load(new InputStreamReader(new FileInputStream("properties_file"), "UTF8"));
when in kotlin it will look like this :
editText.setOnFocusChangeListener { view, hasFocus ->
if (hasFocus) toast("focused") else toast("focuse lose")
}
Be careful, because none of these methods work with a large number of files. Personally, I used this line:
for i in $(ls | grep ".txt");do cat $i >> output.txt;done
EDIT: As someone said in the comments, you can replace $(ls | grep ".txt")
with $(ls *.txt)
EDIT: thanks to @gnourf_gnourf expertise, the use of glob is the correct way to iterate over files in a directory. Consequently, blasphemous expressions like $(ls | grep ".txt")
must be replaced by *.txt
(see the article here).
Good Solution
for i in *.txt;do cat $i >> output.txt;done
I just found this question while on a quest to do the same thing.
After some experimenting I came across an answer that works the way the OQ would want and is simple as heck, but not very general purpose.
Create a shortcut on your desktop or elsewhere (you can use the create-shortcut helper from the right-click menu), set it to run the program "cmd.exe" and run it. When the window opens, position it where you want your window to be. To save that position, bring up the properties menu and hit "Save".
Now if you want you can also set other properties like colors and I highly recommend changing the buffer to be a width of 120-240 and the height to 9999 and enable quick edit mode (why aren't these the defaults!?!)
Now you have a shortcut that will work. Make one of these for each CMD window you want opened at a different location.
Now for the trick, the windows CMD START command can run shortcuts. You can't programmatically reposition the windows before launch, but at least it comes up where you want and you can launch it (and others) from a batch file or another program.
Using a shortcut with cmd /c you can create one shortcut that can launch ALL your links at once by using a command that looks like this:
cmd /c "start cmd_link1 && start cmd_link2 && start cmd_link3"
This will open up all your command windows to your favorite positions and individually set properties like foreground color, background color, font, administrator mode, quick-edit mode, etc... with a single click. Now move that one "link" into your startup folder and you've got an auto-state restore with no external programs at all.
This is a pretty straight-forward solution. It's not general purpose, but I believe it will solve the problem that most people reading this question are trying to solve.
I did this recently so I'll post my cmd file here:
cd /d C:\shortucts
for %%f in (*.lnk *.rdp *.url) do start %%f
exit
Late EDIT: I didn't mention that if the original cmd /c command is run elevated then every one of your windows can (if elevation was selected) start elevated without individually re-prompting you. This has been really handy as I start 3 cmd windows and 3 other apps all elevated every time I start my computer.
I'm surprised this pure bash solution didn't come up:
a="someletters_12345_moreleters.ext"
IFS="_"
set $a
echo $2
# prints 12345
You probably want to reset IFS to what value it was before, or unset IFS
afterwards!
The following solution will work for Bootstrap 4.
.modal .modal-dialog {
max-width: 850px;
}
Out of memory in android application is very common if we not handle the bitmap properly, The solution for the problem would be
if(imageBitmap != null) {
imageBitmap.recycle();
imageBitmap = null;
}
System.gc();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
imageBitmap = BitmapFactory.decodeFile(URI, options);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(imageBitmap, 200, 200, true);
imageView.setImageBitmap(scaledBitmap);
In the above code Have just tried to recycle the bitmap which will allow you to free up the used memory space ,so out of memory may not happen.I have tried it worked for me.
If still facing the problem you can also add these line as well
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
options.inPurgeable = true;
for more information take a look at this link
NOTE: Due to the momentary "pause" caused by performing gc, it is not recommended to do this before each bitmap allocation.
Optimum design is:
Free all bitmaps that are no longer needed, by the if / recycle / null
code shown. (Make a method to help with that.)
System.gc();
Allocate the new bitmaps.
I saw this error when my header file was missing closing brackets.
Causing this error:
// Obj.h
class Obj {
public:
Obj();
Fixing this error:
// Obj.h
class Obj {
public:
Obj();
};
You may run:
git log <SHA1>..HEAD --ancestry-path --merges
From comment of last commit in the output you may find original branch name
Example:
c---e---g--- feature
/ \
-a---b---d---f---h---j--- master
git log e..master --ancestry-path --merges
commit h
Merge: g f
Author: Eugen Konkov <>
Date: Sat Oct 1 00:54:18 2016 +0300
Merge branch 'feature' into master
You can try lubridate package which makes life much easier
library(lubridate)
mdy_hms(mydate)
The above will change the date format to POSIXct
A sample working example:
> data <- "1/15/2006 01:15:00"
> library(lubridate)
> mydate <- mdy_hms(data)
> mydate
[1] "2006-01-15 01:15:00 UTC"
> class(mydate)
[1] "POSIXct" "POSIXt"
For case with factor use as.character
data <- factor("1/15/2006 01:15:00")
library(lubridate)
mydate <- mdy_hms(as.character(data))
I've searched far and wide for a solution to this problem for a long time. Ideally we want to have the child greater than the parent, but without knowing the constraints of the parent in advance.
And I finally found a brilliant generic answer here. Copying it verbatim:
The idea here is: push the container to the exact middle of the browser window with left: 50%;, then pull it back to the left edge with negative -50vw margin.
.child-div {
width: 100vw;
position: relative;
left: 50%;
right: 50%;
margin-left: -50vw;
margin-right: -50vw;
}
Updated Feb 2018: OpenBrace Limited has closed down, and its ObMimic product is no longer supported.
Here's another alternative, using OpenBrace's ObMimic library of Servlet API test-doubles (disclosure: I'm its developer).
package com.openbrace.experiments.examplecode.stackoverflow5434419;
import static org.junit.Assert.*;
import com.openbrace.experiments.examplecode.stackoverflow5434419.YourServlet;
import com.openbrace.obmimic.mimic.servlet.ServletConfigMimic;
import com.openbrace.obmimic.mimic.servlet.http.HttpServletRequestMimic;
import com.openbrace.obmimic.mimic.servlet.http.HttpServletResponseMimic;
import com.openbrace.obmimic.substate.servlet.RequestParameters;
import org.junit.Before;
import org.junit.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Example tests for {@link YourServlet#doPost(HttpServletRequest,
* HttpServletResponse)}.
*
* @author Mike Kaufman, OpenBrace Limited
*/
public class YourServletTest {
/** The servlet to be tested by this instance's test. */
private YourServlet servlet;
/** The "mimic" request to be used in this instance's test. */
private HttpServletRequestMimic request;
/** The "mimic" response to be used in this instance's test. */
private HttpServletResponseMimic response;
/**
* Create an initialized servlet and a request and response for this
* instance's test.
*
* @throws ServletException if the servlet's init method throws such an
* exception.
*/
@Before
public void setUp() throws ServletException {
/*
* Note that for the simple servlet and tests involved:
* - We don't need anything particular in the servlet's ServletConfig.
* - The ServletContext isn't relevant, so ObMimic can be left to use
* its default ServletContext for everything.
*/
servlet = new YourServlet();
servlet.init(new ServletConfigMimic());
request = new HttpServletRequestMimic();
response = new HttpServletResponseMimic();
}
/**
* Test the doPost method with example argument values.
*
* @throws ServletException if the servlet throws such an exception.
* @throws IOException if the servlet throws such an exception.
*/
@Test
public void testYourServletDoPostWithExampleArguments()
throws ServletException, IOException {
// Configure the request. In this case, all we need are the three
// request parameters.
RequestParameters parameters
= request.getMimicState().getRequestParameters();
parameters.set("username", "mike");
parameters.set("password", "xyz#zyx");
parameters.set("name", "Mike");
// Run the "doPost".
servlet.doPost(request, response);
// Check the response's Content-Type, Cache-Control header and
// body content.
assertEquals("text/html; charset=ISO-8859-1",
response.getMimicState().getContentType());
assertArrayEquals(new String[] { "no-cache" },
response.getMimicState().getHeaders().getValues("Cache-Control"));
assertEquals("...expected result from dataManager.register...",
response.getMimicState().getBodyContentAsString());
}
}
Notes:
Each "mimic" has a "mimicState" object for its logical state. This provides a clear distinction between the Servlet API methods and the configuration and inspection of the mimic's internal state.
You might be surprised that the check of Content-Type includes "charset=ISO-8859-1". However, for the given "doPost" code this is as per the Servlet API Javadoc, and the HttpServletResponse's own getContentType method, and the actual Content-Type header produced on e.g. Glassfish 3. You might not realise this if using normal mock objects and your own expectations of the API's behaviour. In this case it probably doesn't matter, but in more complex cases this is the sort of unanticipated API behaviour that can make a bit of a mockery of mocks!
I've used response.getMimicState().getContentType()
as the simplest way to check Content-Type and illustrate the above point, but you could indeed check for "text/html" on its own if you wanted (using response.getMimicState().getContentTypeMimeType()
). Checking the Content-Type header the same way as for the Cache-Control header also works.
For this example the response content is checked as character data (with this using the Writer's encoding). We could also check that the response's Writer was used rather than its OutputStream (using response.getMimicState().isWritingCharacterContent()
), but I've taken it that we're only concerned with the resulting output, and don't care what API calls produced it (though that could be checked too...). It's also possible to retrieve the response's body content as bytes, examine the detailed state of the Writer/OutputStream etc.
There are full details of ObMimic and a free download at the OpenBrace website. Or you can contact me if you have any questions (contact details are on the website).
-webkit-overflow-scrolling:touch
as mentioned in the answer is infact the possible solution.
<div style="overflow:scroll !important; -webkit-overflow-scrolling:touch !important;">
<iframe src="YOUR_PAGE_URL" width="600" height="400"></iframe>
</div>
But if you are unable to scroll up and down inside the iframe as shown in image below,
you could try scrolling with 2 fingers diagonally like this,
This actually worked in my case, so just sharing it if you haven't still found a solution for this.
UPDATE: Now it's very simple to add HTML attributes to the default editor templates. It neans instead of doing this:
@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })
you simply can do this:
@Html.EditorFor(m => m.userCode, new { htmlAttributes = new { @readonly="readonly" } })
Benefits: You haven't to call .TextBoxFor
, etc. for templates. Just call .EditorFor
.
While @Shark's solution works correctly, and it is simple and useful, my solution (that I use always) is this one: Create an editor-template
that can handles readonly
attribute:
EditorTemplates
in ~/Views/Shared/
PartialView
named String.cshtml
Fill the String.cshtml
with this code:
@if(ViewData.ModelMetadata.IsReadOnly) {
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { @class = "text-box single-line readonly", @readonly = "readonly", disabled = "disabled" })
} else {
@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
new { @class = "text-box single-line" })
}
In model class, put the [ReadOnly(true)]
attribute on properties which you want to be readonly
.
For example,
public class Model {
// [your-annotations-here]
public string EditablePropertyExample { get; set; }
// [your-annotations-here]
[ReadOnly(true)]
public string ReadOnlyPropertyExample { get; set; }
}
Now you can use Razor's default syntax simply:
@Html.EditorFor(m => m.EditablePropertyExample)
@Html.EditorFor(m => m.ReadOnlyPropertyExample)
The first one renders a normal text-box
like this:
<input class="text-box single-line" id="field-id" name="field-name" />
And the second will render to;
<input readonly="readonly" disabled="disabled" class="text-box single-line readonly" id="field-id" name="field-name" />
You can use this solution for any type of data (DateTime
, DateTimeOffset
, DataType.Text
, DataType.MultilineText
and so on). Just create an editor-template
.
In my opinion the accepted answer is in most cases an overkill.
The cause of the error is often mismatch of BEGIN and COMMIT as clearly stated by the error. This means using:
Begin
Begin
-- your query here
End
commit
instead of
Begin Transaction
Begin
-- your query here
End
commit
omitting Transaction after Begin causes this error!
Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :
select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';
You can add any condition or ignore based on your requirement.
The output of the query is resulted as :
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| 5 | ssss | localhost:41060 | somedb | Sleep | 3 | | NULL |
| 58169 | root | localhost | somedb | Query | 0 | executing | select * from sometable where tblColumnName = 'someName' |
Once you have started tomcat simply run the following command at a terminal prompt:
ps -ef | grep tomcat
This will show the process details and indicate which JVM (by folder location) is running tomcat.
This is an answer to @craq :
I just compiled the file from C source and set it to be executable with chmod. There were no warning or error messages from gcc.
I'm a bit surprised that you had to 'set it to executable' -- my gcc
always sets the executable flag itself. This suggests to me that gcc
didn't expect this to be the final executable file, or that it didn't expect it to be executable on this system.
Now I've tried to just create the object file, like so:
$ gcc -c -o hello hello.c
$ chmod +x hello
(hello.c
is a typical "Hello World" program.) But my error message is a bit different:
$ ./hello
bash: ./hello: cannot execute binary file: Exec format error`
On the other hand, this way, the output of the file
command is identical to yours:
$ file hello
hello: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
Whereas if I compile correctly, its output is much longer.
$ gcc -o hello hello.c
$ file hello
hello: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=131bb123a67dd3089d23d5aaaa65a79c4c6a0ef7, not stripped
What I am saying is: I suspect it has something to do with the way you compile and link your code. Maybe you can shed some light on how you do that?
It is possible to provide a class or other information through AdditionalViewData - I use this where I'm allowing a user to create a form based on database fields (propertyName, editorType, and editorClass).
Based on your initial example:
@Html.EditorFor(x => x.Created, new { cssClass = "date" })
and in the custom template:
<div>
@Html.TextBoxFor(x => x.Created, new { @class = ViewData["cssClass"] })
</div>
The problem here is twofold
fgetc()
returns an int instead of a char.The first is easily fixed:
char *orig = code; // the beginning of the array
// ...
do {
*code = fgetc(file);
} while(*code++ != EOF);
*code = '\0'; // nul-terminate the string
return orig; // don't return a pointer to the end
The second problem is more subtle -fgetc
returns an int so that the EOF
value can be distinguished from any possible char value. Fixing this uses a temporary int for the EOF
check and probably a regular while loop instead of do / while.
he does an integer divide, which means 3 / 4 = 0. cast one of the brackets to float
(float)(a.y - b.y) / (a.x - b.x);
If none of the other answers work for you then try the following which was the only thing that worked for me:
Find your .csproj
file and edit it in a text editor.
Find the <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
tag in your .csproj
file and delete the whole block.
Re-install all packages in the solution:
Update-Package -reinstall
After this your nuget packages should be restored, i think this might be a fringe case that only occurs when you move your project to a different location.
I use npm-check
to achieve this.
npm i -g npm npm-check
npm-check -ug #to update globals
npm-check -u #to update locals
Another useful command list which will keep exact version numbers in package.json
npm cache clean
rm -rf node_modules/
npm i -g npm npm-check-updates
ncu -g #update globals
ncu -ua #update locals
npm i
When you create your Process
object set StartInfo
appropriately:
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "program.exe",
Arguments = "command line arguments to your executable",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
then start the process and read from it:
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
// do something with line
}
You can use int.Parse()
or int.TryParse()
to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.
removeChild
should be invoked on the parent, i.e.:
parent.removeChild(child);
In your example, you should be doing something like:
if (frameid) {
frameid.parentNode.removeChild(frameid);
}
Set up HADOOP_HOME variable in windows to resolve the problem.
You can find answer in org/apache/hadoop/hadoop-common/2.2.0/hadoop-common-2.2.0-sources.jar!/org/apache/hadoop/util/Shell.java
:
IOException from
public static final String getQualifiedBinPath(String executable)
throws IOException {
// construct hadoop bin path to the specified executable
String fullExeName = HADOOP_HOME_DIR + File.separator + "bin"
+ File.separator + executable;
File exeFile = new File(fullExeName);
if (!exeFile.exists()) {
throw new IOException("Could not locate executable " + fullExeName
+ " in the Hadoop binaries.");
}
return exeFile.getCanonicalPath();
}
HADOOP_HOME_DIR from
// first check the Dflag hadoop.home.dir with JVM scope
String home = System.getProperty("hadoop.home.dir");
// fall back to the system/user-global env variable
if (home == null) {
home = System.getenv("HADOOP_HOME");
}
when using varchar values SQL Server needs an additional 2 bytes per row to store some info about that column whereas if you use char it doesn't need that so unless you
This is more understandable:
git checkout 56e05fced -- .
git add .
git commit -m 'Revert to 56e05fced'
And to prove that it worked:
git diff 56e05fced
Hrrm... I dont know how many times this has happend so far: I test, try, google, test again and mess around for hours, and when I finally give up, I go to my trusted Stackoverflow and write a detailed and clear question.
When I post the question, switch over to the IDE and boom - error gone.
I can't say why its gone, because I change absolutely nothing in the code except for that I already tried as stated above. But all of a sudden, the compile error is gone!
In the build.gradle, it now says:
dependencies {
compile "com.android.support:appcompat-v7:18.0.+"
}
which initially did not work, the compile errors did not go away. it took like 30 min before the IDE got it, it seems... hmm...
=== EDIT === When I view the build.gradle again, it has now changed and looks like this:
dependencies {
compile 'com.android.support:support-v4:18.0.0'
compile "com.android.support:appcompat-v7:18.0.+"
}
Im not really sure what the appcompat is right now.
After you start running the training loop, if you want to manually watch it from the terminal whether your program is utilizing the GPU resources and to what extent, then you can simply use watch
as in:
$ watch -n 2 nvidia-smi
This will continuously update the usage stats for every 2 seconds until you press ctrl+c
If you need more control on more GPU stats you might need, you can use more sophisticated version of nvidia-smi
with --query-gpu=...
. Below is a simple illustration of this:
$ watch -n 3 nvidia-smi --query-gpu=index,gpu_name,memory.total,memory.used,memory.free,temperature.gpu,pstate,utilization.gpu,utilization.memory --format=csv
which would output the stats something like:
Note: There should not be any space between the comma separated query names in --query-gpu=...
. Else those values will be ignored and no stats are returned.
Also, you can check whether your installation of PyTorch detects your CUDA installation correctly by doing:
In [13]: import torch
In [14]: torch.cuda.is_available()
Out[14]: True
True
status means that PyTorch is configured correctly and is using the GPU although you have to move/place the tensors with necessary statements in your code.
If you want to do this inside Python code, then look into this module:
https://github.com/jonsafari/nvidia-ml-py or in pypi here: https://pypi.python.org/pypi/nvidia-ml-py/
As of now when pip has upgraded to 10 and now they have changed their path from pypi.python.org to files.pythonhosted.org Please update the command to pip --trusted-host files.pythonhosted.org install python_package
For those who want to set a computed or dynamic property on the window
object, you'll find that not possible with the declare global
method. To clarify for this use case
window[DynamicObject.key] // Element implicitly has an 'any' type because type Window has no index signature
You might attempt to do something like this
declare global {
interface Window {
[DyanmicObject.key]: string; // error RIP
}
}
The above will error though. This is because in Typescript, interfaces do not play well with computed properties and will throw an error like
A computed property name in an interface must directly refer to a built-in symbol
To get around this, you can go with the suggest of casting window
to <any>
so you can do
(window as any)[DynamicObject.key]
There's a headers parameter in the config object you pass to $http
for per-call headers:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Or with the shortcut method:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
The list of the valid parameters is available in the $http service documentation.
If it's a table-value function (returns a table set) you simply join it as a Table
this function generates one column table with all the values from passed comma-separated list
SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')
If the .c source files are converted .cpp (like as in parsec), then the extern needs to be followed by "C" as in
extern "C" void foo();
After two days of going through the web, this is what I came up with in Kotlin. Tested and works on my app
private fun setupActionBar() {
supportActionBar?.apply {
displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
displayOptions = ActionBar.DISPLAY_SHOW_TITLE
setDisplayShowCustomEnabled(true)
title = ""
val titleTextView = AppCompatTextView(this@MainActivity)
titleTextView.text = getText(R.string.app_name)
titleTextView.setSingleLine()
titleTextView.textSize = 24f
titleTextView.setTextColor(ContextCompat.getColor(this@MainActivity, R.color.appWhite))
val layoutParams = ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT
)
layoutParams.gravity = Gravity.CENTER
setCustomView(titleTextView, layoutParams)
setBackgroundDrawable(
ColorDrawable(
ContextCompat.getColor(
this@MainActivity,
R.color.appDarkBlue
)
)
)
}
}
You need to set$final[$id]
to an array before adding elements to it. Intiialize it with either
$final[$id] = array();
$final[$id][0] = 3;
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
or
$final[$id] = array(0 => 3);
$final[$id]['link'] = "/".$row['permalink'];
$final[$id]['title'] = $row['title'];
You need to set utf8mb4 in meta html and also in your server alter tabel and set collation to utf8mb4
I tried using it and didn't work, guess it's just the modal versioin.
Although, it worked as this:
$("#myModal").on("hide.bs.modal", function () {
// put your default event here
});
Just to update the answer =)
So, something like the $_POST
array?
You can use http_build_query($_POST)
to get them in a var=xxx&var2=yyy
string again. Or just print_r($_POST)
to see what's there.
I still go with the uppercase for const values, but this is more out of habit than for any particular reason.
Of course it makes it easy to see immediately that something is a const. The question to me is: Do we really need this information? Does it help us in any way to avoid errors? If I assign a value to the const, the compiler will tell me I did something dumb.
My conclusion: Go with the camel casing. Maybe I will change my style too ;-)
Edit:
That something smells hungarian is not really a valid argument, IMO. The question should always be: Does it help, or does it hurt?
There are cases when hungarian helps. Not that many nowadays, but they still exist.
You could use Extension
method to switch between Regular Style and Bold Style as below:
static class Helper
{
public static void SwtichToBoldRegular(this TextBox c)
{
if (c.Font.Style!= FontStyle.Bold)
c.Font = new Font(c.Font, FontStyle.Bold);
else
c.Font = new Font(c.Font, FontStyle.Regular);
}
}
And usage:
textBox1.SwtichToBoldRegular();
Just to mention, you can also use the default a theme like android.R.style.Theme_DeviceDefault_Light_Dialog
instead.
new DatePickerDialog(MainActivity.this, android.R.style.Theme_DeviceDefault_Light_Dialog, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//DO SOMETHING
}
}, 2015, 02, 26).show();
Delete everything inside your local copy using:
rm -r your_local_svn_dir_path/*
And the revert everything recursively using the below command.
svn revert -R your_local_svn_dir_path
This is way faster than deleting the entire directory and then taking a fresh checkout, because the files are being restored from you local SVN meta data. It doesn't even need a network connection.
For what its worth, I couldn't get it working on IE7/8/9 and the multiple declaration option didn't make any difference.
The fix for me was as a result of the instructions on the Technical Considerations Page where it highlights...
For best display in IE, make the stylesheet 'link' tag the first element in the HTML 'head' section.
Works across IE7/8/9 for me now.
var str = 'abcdefghijkl';_x000D_
console.log(str.match(/.{1,3}/g));
_x000D_
Note: Use {1,3}
instead of just {3}
to include the remainder for string lengths that aren't a multiple of 3, e.g:
console.log("abcd".match(/.{1,3}/g)); // ["abc", "d"]
_x000D_
A couple more subtleties:
.
won't capture those. Use /[\s\S]{1,3}/
instead. (Thanks @Mike).match()
will return null
when you may be expecting an empty array. Protect against this by appending || []
.So you may end up with:
var str = 'abcdef \t\r\nghijkl';_x000D_
var parts = str.match(/[\s\S]{1,3}/g) || [];_x000D_
console.log(parts);_x000D_
_x000D_
console.log(''.match(/[\s\S]{1,3}/g) || []);
_x000D_
There's a bit of confusion in your question:
Date
datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE
into a Date
.TO_CHAR
function. In Oracle, a Date
has no format: it is a point in time.TO_TIMESTAMP_TZ
to convert a VARCHAR2
to a TIMESTAMP
, but this won't convert a Date
to a TIMESTAMP
.FROM_TZ
to add the time zone information to a TIMESTAMP
(or a Date
).CST
is a time zone but CDT
is not. CDT
is a daylight saving information.CST/CDT
(-05:00
) and CST/CST
(-06:00
) will have different values obviously, but the time zone CST
will inherit the daylight saving information depending upon the date by default.So your conversion may not be as simple as it looks.
Assuming that you want to convert a Date
d
that you know is valid at time zone CST/CST
to the equivalent at time zone CST/CDT
, you would use:
SQL> SELECT from_tz(d, '-06:00') initial_ts,
2 from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
3 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
4 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
5 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00
My default timestamp format has been used here. I can specify a format explicitely:
SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
2 to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
3 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
4 FROM (SELECT cast(to_date('2012-10-09 01:10:21',
5 'yyyy-mm-dd hh24:mi:ss') as timestamp) d
6 FROM dual);
INITIAL_TS CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00 2012-10-09 02:10:21 -05:00
Use new Date(dateString)
if your string is compatible with Date.parse()
. If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.
Setting default choice for symfony2 radio button
$builder->add('range_options', 'choice', array(
'choices' => array('day'=>'Day', 'week'=>'Week', 'month'=>'Month'),
'data'=>'day', //set default value
'required'=>true,
'empty_data'=>null,
'multiple'=>false,
'expanded'=> true
))
I had the same problem. In the jQuery documentation I found:
For cross-domain requests, setting the content type to anything other than
application/x-www-form-urlencoded
,multipart/form-data
, ortext/plain
will trigger the browser to send a preflight OPTIONS request to the server.
So though the server allows cross origin request but does not allow Access-Control-Allow-Headers
, it will throw errors. By default angular content type is application/json
, which is trying to send a OPTION request. Try to overwrite angular default header or allow Access-Control-Allow-Headers
in server end. Here is an angular sample:
$http.post(url, data, {
headers : {
'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
}
});
All of them are good in their own ways - They're simply different approaches to the same problems.
In a purely procedural style, data tends to be highly decoupled from the functions that operate on it.
In an object oriented style, data tends to carry with it a collection of functions.
In a functional style, data and functions tend toward having more in common with each other (as in Lisp and Scheme) while offering more flexibility in terms of how functions are actually used. Algorithms tend also to be defined in terms of recursion and composition rather than loops and iteration.
Of course, the language itself only influences which style is preferred. Even in a pure-functional language like Haskell, you can write in a procedural style (though that is highly discouraged), and even in a procedural language like C, you can program in an object-oriented style (such as in the GTK+ and EFL APIs).
To be clear, the "advantage" of each paradigm is simply in the modeling of your algorithms and data structures. If, for example, your algorithm involves lists and trees, a functional algorithm may be the most sensible. Or, if, for example, your data is highly structured, it may make more sense to compose it as objects if that is the native paradigm of your language - or, it could just as easily be written as a functional abstraction of monads, which is the native paradigm of languages like Haskell or ML.
The choice of which you use is simply what makes more sense for your project and the abstractions your language supports.
As MDN Window.history() describes :
For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.
For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.
There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.
So there is no Javascript method to clear the session history, instead, if you want to block navigating back to a certain page, you can use the location.replace() method, and pass the page link as parameter, which will not push the page to the browser's session history list. For example, there are three pages:
a.html:
<!doctype html>
<html>
<head>
<title>a.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">a.html</code> page ! Go to <a href="b.html">b.html</a> page !</p>
</body>
</html>
b.html:
<!doctype html>
<html>
<head>
<title>b.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">b.html</code> page ! Go to <a id="jumper" href="c.html">c.html</a> page !</p>
<script type="text/javascript">
var jumper = document.getElementById("jumper");
jumper.onclick = function(event) {
var e = event || window.event ;
if(e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = true ;
}
location.replace(this.href);
jumper = null;
}
</script>
</body>
c.html:
<!doctype html>
<html>
<head>
<title>c.html page</title>
<meta charset="utf-8">
</head>
<body>
<p>This is <code style="color:red">c.html</code> page</p>
</body>
</html>
With href link, we can navigate from a.html to b.html to c.html. In b.html, we use the location.replace(c.html)
method to navigate from b.html to c.html. Finally, we go to c.html*, and if we click the back button in the browser, we will jump to **a.html.
So this is it! Hope it helps.
document.write("\n");
won't work if you're executing it (document.write();
) multiple times.
I'll suggest you should go for:
document.write("<br>");
P.S I know people have stated this answer above but didn't find the difference anywhere so :)
The documents on fs.stat()
says to use fs.access()
if you are not going to manipulate the file. It did not give a justification, might be faster or less memeory use?
I use node for linear automation, so I thought I share the function I use to test for file existence.
var fs = require("fs");
function exists(path){
//Remember file access time will slow your program.
try{
fs.accessSync(path);
} catch (err){
return false;
}
return true;
}
You have a PivotTables collection on a the VB Worksheet object. So, a quick loop like this will work:
Sub RefreshPivotTables()
Dim pivotTable As PivotTable
For Each pivotTable In ActiveSheet.PivotTables
pivotTable.RefreshTable
Next
End Sub
Notes from the trenches:
Good luck!
Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:
// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');
// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';
// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
// Parse the request URL. Relative URLs require an origin explicitly.
const url = new URL(request.url, serverOrigin);
// Parse the URL query. The leading '?' has to be removed before this.
const query = parseQuery(url.search.substr(1));
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(`Hello, ${query.name}!\n`);
});
// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);
// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);
If you run the script above, you can test the server response like this, for example:
curl -q http://localhost:8000/status?name=ryan
Hello, ryan!
I would create a trigger that catches all updates/inserts/deletes and write timestamp in custom table, something like tablename | timestamp
Just because I don't like the idea to read internal system tables of db server directly
... right now it happens only to the website I'm testing. I can't post it here because it's confidential.
Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use
--secure-protocol=TLSv1
. If this does not help check if you can access the site with openssl s_client -connect ...
(probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ...
.
Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.
The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.
Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?
The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.
querySelector
and querySelectorAll
are a relatively new APIs, whereas getElementById
and getElementsByClassName
have been with us for a lot longer. That means that what you use will mostly depend on which browsers you need to support.
As for the :
, it has a special meaning so you have to escape it if you have to use it as a part of a ID/class name.
Besides using std::find
(from algorithm), you can also use std::find_if
(which is, IMO, better than std::find), or other find algorithm from this list
#include <list>
#include <algorithm>
#include <iostream>
int main()
{
std::list<int> myList{ 5, 19, 34, 3, 33 };
auto it = std::find_if( std::begin( myList ),
std::end( myList ),
[&]( const int v ){ return 0 == ( v % 17 ); } );
if ( myList.end() == it )
{
std::cout << "item not found" << std::endl;
}
else
{
const int pos = std::distance( myList.begin(), it ) + 1;
std::cout << "item divisible by 17 found at position " << pos << std::endl;
}
}
So you can utilize short-circuiting:
bool containsBoth = compareString.Contains(firstString) &&
compareString.Contains(secondString);
I found this detailed post about how to open (attach) the MDF file in SQL Server Management Studio: http://learningsqlserver.wordpress.com/2011/02/13/how-can-i-open-mdf-and-ldf-files-in-sql-server-attach-tutorial-troublshooting/
I also have the issue of not being able to navigate to the file. The reason is most likely this:
The reason it won't "open" the folder is because the service account running the SQL Server Engine service does not have read permission on the folder in question. Assign the windows user group for that SQL Server instance the rights to read and list contents at the WINDOWS level. Then you should see the files that you want to attach inside of the folder.
One solution to this problem is described here: http://technet.microsoft.com/en-us/library/jj219062.aspx I haven't tried this myself yet. Once I do, I'll update the answer.
Hope this helps.
A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.
// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
// set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
var postEnc, method;
if (post == null)
{
postEnc = '';
method = 'GET';
}
else
{
method = 'POST';
postEnc = new FormData();
for(var i in post)
postEnc.append(i, post[i]);
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200)
{
var res = this.response;
var reader = new window.FileReader();
reader.readAsDataURL(res);
reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
}
}
xhr.open(method, url);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('fname=Henry&lname=Ford');
xhr.responseType = 'blob';
xhr.send(postEnc);
}
You seek the all-powerful *?
From the docs, Greedy versus Non-Greedy
the non-greedy qualifiers
*?
,+?
,??
, or{m,n}?
[...] match as little text as possible.
// This is a working Notification
private static final int NotificID=01;
b= (Button) findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Notification notification=new Notification.Builder(MainActivity.this)
.setContentTitle("Notification Title")
.setContentText("Notification Description")
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NotificID,notification);
}
});
}
libiconv is a great library for all our encoding and decoding needs.
If you are using Windows you can use WideCharToMultiByte and specify that you want UTF8.
I'm using IronPython here (same as .NET API) and reading the file as UTF-8 in order to properly handle the BOM fixed the problem for me:
xmlFile = Path.Combine(directory_str, 'file.xml')
doc = XPathDocument(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))
It would work as well with the XmlDocument
:
doc = XmlDocument()
doc.Load(XmlTextReader(StreamReader(xmlFile.ToString(), Encoding.UTF8)))
Don't define variables in headers. Put declarations in header and definitions in one of the .c files.
In config.h
extern const char *names[];
In some .c file:
const char *names[] =
{
"brian", "stefan", "steve"
};
If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.
Just change the permission of tmp_file_upload to 755 Following is the command chmod -R 755 tmp_file_upload
Check if you're response[0]
actually exists, the error seems to suggest it doesn't.
my 2 cents
def getResponseCode(url):
conn = urllib.request.urlopen(url)
return conn.getcode()
if getResponseCode(url) != 200:
print('Wrong URL')
else:
print('Good URL')
I was also facing this error. The error has been fixed by changing content of core function getRowUrl in app\code\core\Mage\Adminhtml\Block\Widget\Grid.php The core function is :
public function getRowUrl($item)
{
$res = parent::getRowUrl($item);
return ($res ? $res : ‘#’);
}
Replaced with :
public function getRowUrl($item)
{
return $this->getUrl(’*/*/edit’, array(’id’ => $item->getId()));
}
For more detail : http://bit.ly/iTKcer
Enjoy!!!!!!!!!!!!!
You can make it by one line:
mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
fmt.Println("k:", k, "v:", v)
}
Output is:
k: foo v: map[first:1]
k: boo v: map[second:2]
According to W3Schools.com,
The center element was deprecated in HTML 4.01, and is not supported in XHTML 1.0 Strict DTD.
The HTML 4.01 spec gives this reason for deprecating the tag:
The CENTER element is exactly equivalent to specifying the DIV element with the align attribute set to "center".
Try not closing the connection before you send data to your database. Remove client.close();
from your code and it'll work fine.
Here is my answer for python 3.
some_string = "2 3 8 61 "
list(map(int, some_string.strip().split()))
Just adding to Frederic's answer, for example if you call your script as follows:
./myscript.py foo bar
sys.argv[0]
would be "./myscript.py"
sys.argv[1]
would be "foo" and
sys.argv[2]
would be "bar" ... and so forth.
In your example code, if you call the script as follows ./myscript.py foo
, the script's output will be "Hello there foo".
This is a slightly different answer to one below that worked for me:
public static validate(control: FormControl): { whitespace: boolean } {_x000D_
const valueNoWhiteSpace = control.value.trim();_x000D_
const isValid = valueNoWhiteSpace === control.value;_x000D_
return isValid ? null : { whitespace: true };_x000D_
}
_x000D_
This is an old question, but this is another way, using jQuery to reuse the popover and to keep using the original bootstrap data attributes to make it more semantic:
<a href="#" rel="popover" data-trigger="focus" data-popover-content="#popover">
Show it!
</a>
<!-- Let's show the Bootstrap nav on the popover-->
<div id="list-popover" class="hide">
<ul class="nav nav-pills nav-stacked">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
$('[rel="popover"]').popover({
container: 'body',
html: true,
content: function () {
var clone = $($(this).data('popover-content')).clone(true).removeClass('hide');
return clone;
}
});
Fiddle with complete example: http://jsfiddle.net/tomsarduy/262w45L5/
When you iterate through dictionaries using the for .. in ..
-syntax, it always iterates over the keys (the values are accessible using dictionary[key]
).
To iterate over key-value pairs, in Python 2 use for k,v in s.iteritems()
, and in Python 3 for k,v in s.items()
.
Using Swift 3
func validate(value: String) -> Bool {
let PHONE_REGEX = "^\\d{3}-\\d{3}-\\d{4}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", PHONE_REGEX)
let result = phoneTest.evaluate(with: value)
return result
}
If you want to always display some value after decimal for example "12.00" or "12.23" Then use just like below , it worked for me
FormatNumber("145.231000",2)
Which will display 145.23
FormatNumber("145",2)
Which will display 145.00
I used @timestamp
instead of _timestamp
{
'size' : 1,
'query': {
'match_all' : {}
},
"sort" : [{"@timestamp":{"order": "desc"}}]
}
One line code to detect the browser.
If the browser is IE or Edge, It will return true;
let isIE = /edge|msie\s|trident\//i.test(window.navigator.userAgent)
The simplest way is to use itertools.product
:
a = ["foo", "melon"]
b = [True, False]
c = list(itertools.product(a, b))
>> [("foo", True), ("foo", False), ("melon", True), ("melon", False)]
What I was doing was starting a new activity and then closing the current activity. So, remember this simple rule:
finish()
startActivity<...>()
and not
startActivity<...>()
finish()
For using a proxy with https I tried the advice on this website (using dependency https-proxy-agent) and it worked for me:
http://codingmiles.com/node-js-making-https-request-via-proxy/
you can also use $rootScope
to call a function/method of 1st controller from second controller like this,
.controller('ctrl1', function($rootScope, $scope) {
$rootScope.methodOf2ndCtrl();
//Your code here.
})
.controller('ctrl2', function($rootScope, $scope) {
$rootScope.methodOf2ndCtrl = function() {
//Your code here.
}
})
Following is my project structure:
ProjectFolder:
- project:
- __init__.py
- item.py
- tests:
- test_item.py
I found it better to import in the setUp() method:
import unittest
import sys
class ItemTest(unittest.TestCase):
def setUp(self):
sys.path.insert(0, "../project")
from project import item
# further setup using this import
def test_item_props(self):
# do my assertions
if __name__ == "__main__":
unittest.main()
The user has the ability to kill his own programs, using kill or Control+C, but I get the impression that's not what happened, and that the user complained to you.
root has the ability to kill programs of course, but if someone has root on your machine and is killing stuff you have bigger problems.
If you are not the sysadmin, the sysadmin may have set up quotas on CPU, RAM, ort disk usage and auto-kills processes that exceed them.
Other than those guesses, I'm not sure without more info about the program.
This is an old question. But if you're using a virtualenv with python, place the contents of the downloaded libav bin
folder in the Scripts
folder of your virtualenv.
The major difference between require
and import
, is that require
will automatically scan node_modules
to find modules, but import
, which comes from ES6, won't.
Most people use babel to compile import
and export
, which makes import
act the same as require
.
The future version of Node.js might support import
itself (actually, the experimental version already does), and judging by Node.js' notes, import
won't support node_modules
, it base on ES6, and must specify the path of the module.
So I would suggest you not use import
with babel, but this feature is not yet confirmed, it might support node_modules
in the future, who would know?
For reference, below is an example of how babel can convert ES6's import
syntax to CommonJS's require
syntax.
Say the fileapp_es6.js
contains this import:
import format from 'date-fns/format';
This is a directive to import the format function from the node package date-fns.
The related package.json
file could contain something like this:
"scripts": {
"start": "node app.js",
"build-server-file": "babel app_es6.js --out-file app.js",
"webpack": "webpack"
}
The related .babelrc
file could be something like this:
{
"presets": [
[
"env",
{
"targets":
{
"node": "current"
}
}
]
]
}
This build-server-file
script defined in the package.json
file is a directive for babel to parse the app_es6.js
file and output the file app.js
.
After running the build-server-file
script, if you open app.js
and look for the date-fns
import, you will see it has been converted into this:
var _format = require("date-fns/format");
var _format2 = _interopRequireDefault(_format);
Most of that file is gobbledygook to most humans, however computers understand it.
Also for reference, as an example of how a module can be created and imported into your project, if you install date-fns
and then open node_modules/date-fns/get_year/index.js
you can see it contains:
var parse = require('../parse/index.js')
function getYear (dirtyDate) {
var date = parse(dirtyDate)
var year = date.getFullYear()
return year
}
module.exports = getYear
Using the babel process above, your app_es6.js
file could then contain:
import getYear from 'date-fns/get_year';
// Which year is 2 July 2014?
var result = getYear(new Date(2014, 6, 2))
//=> 2014
And babel would convert the imports to:
var _get_year = require("date-fns/get_year");
var _get_year2 = _interopRequireDefault(_get_year);
And handle all references to the function accordingly.
Use this:
$('#navigation ul li').css('display', 'inline-block');
Also, as others have stated, if you want to make multiple css changes at once, that's when you would add the curly braces (for object notation), and it would look something like this (if you wanted to change, say, 'background-color' and 'position' in addition to 'display'):
$('#navigation ul li').css({'display': 'inline-block', 'background-color': '#fff', 'position': 'relative'}); //The specific CSS changes after the first one, are, of course, just examples.
You should do ex.StackTrace instead of ex.ToString()
You can Change the speed by adding scrolldelay
<marquee style="font-family: lato; color: #FFFFFF" bgcolor="#00224f" scrolldelay="400">Now the Speed is Delay to 400 Milliseconds</marquee>
_x000D_
Put your params in the data
part of the ajax
call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
In my case I'm using Xcode 10.1. There is a option of switching between plain text and Attributed text in Label text in Interface Builder
Hope this may help someone else..!
use this code for set value in input tag by another id.
$(".formdata").val(document.getElementById("fsd").innerHTML);
or use this code for set value in input tag using classname="formdata"
$(".formdata").val("hello");
You can do by the following ways
this.your_form.getRawValue()['formcontrolname]
this.your_form.value['formcontrolname]
In addition to the answers given above, check the last line of the error message in your console. In my case, the 'site-packages' path in sys.path.append('.....') was wrong.
Since the size of your string array is fixed at compile time, you'd be better off using a structure (like Pair
) that mandates exactly two fields, and thus avoid the runtime errors possible with the array approach.
Code:
Since Java doesn't supply a Pair
class, you'll need to define your own.
class Pair<A, B> {
public final A first;
public final B second;
public Pair(final A first, final B second) {
this.first = first;
this.second = second;
}
//
// Override 'equals', 'hashcode' and 'toString'
//
}
and then use it as:
List<Pair<String, String>> action = new ArrayList<Pair<String, String>>();
[ Here I used List
because it's considered a good practice to program to interfaces. ]
Assuming the column is set to support NULL as a value:
UPDATE YOUR_TABLE
SET column = NULL
Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:
UPDATE YOUR_TABLE
SET column = CAST(NULL AS DATETIME)
...assuming column
is a DATETIME data type in the example above.
Not exactly a setting but you can override the default TrustManager and HostnameVerifier to accept anything. Not a safe approach but in your situation, it can be acceptable.
Complete example : Fix certificate problem in HTTPS
Here's an example to use ngclick & ng-if directives.
Note: that ng-if removes the element from the DOM, but ng-hide just hides the display of the element.
<!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
<input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
<div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
Enter book name: <input type = "text" ng-model = "book.name"><br>
Enter book category: <input type = "text" ng-model = "book.category"><br>
Enter book price: <input type = "text" ng-model = "book.price"><br>
Enter book author: <input type = "text" ng-model = "book.author"><br>
You are entering book: {{book.bookDetails()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('bookController', function($scope) {
$scope.book = {
name: "",
category: "",
price:"",
author: "",
bookDetails: function() {
var bookObject;
bookObject = $scope.book;
return "Book name: " + bookObject.name + '\n' + "Book category: " + bookObject.category + " \n" + "Book price: " + bookObject.price + " \n" + "Book Author: " + bookObject.author;
}
};
});
</script>
I know my answer it's too late, but it might helpful to other's
Try,
Void Main()
{
string filename = @"test.txt";
string filePath= AppDomain.CurrentDomain.BaseDirectory + filename ;
Console.WriteLine(filePath);
}
If your input always has a time zone of "zulu" ("Z" = UTC), then you can use DateTimeFormatter.ISO_INSTANT
(implicitly):
final Instant parsed = Instant.parse(dateTime);
If time zone varies and has the form of "+01:00" or "+01:00:00" (when not "Z"), then you can use DateTimeFormatter.ISO_OFFSET_DATE_TIME
:
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
final ZonedDateTime parsed = ZonedDateTime.parse(dateTime, formatter);
If neither is the case, you can construct a DateTimeFormatter
in the same manner as DateTimeFormatter.ISO_OFFSET_DATE_TIME
is constructed.
Your current pattern has several problems:
ResolverStyle.STRICT
);yyyy
instead of uuuu
(yyyy
will not work in strict mode);hh
instead of 24-hour HH
;S
for fractional seconds, but input has three.CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA
// files to upload
$filename = "https://example.s3.amazonaws.com/0.jpg";
// URL to upload to (Destination server)
$url = "https://otherserver/image";
AND
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($filename),
CURLOPT_HTTPHEADER => array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data",
"Content-Length: " . strlen(file_get_contents($filename)),
"API-Key: abcdefghi" //Optional if required
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";
//print_r($info['request_header']);
var_dump($response);
$err = curl_error($curl);
echo "error";
var_dump($err);
curl_close($curl);
Surely using array_map
and if using a container implementing ArrayAccess
to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()
clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait
cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr
you could always $arr = array_map
and be explicit.
In my case I tried with all the options given here, but no one was working properly (angular 1.3.13, ionic 1.0.0, angular-ui-router 0.2.13). The solution was:
.state('tab.friends', {
url: '/friends/:param1/:param2',
views: {
'tab-friends': {
templateUrl: 'templates/tab-friends.html',
controller: 'FriendsCtrl'
}
}
})
and in the state.go:
$state.go('tab.friends', {param1 : val1, param2 : val2});
Cheers
One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:
import math
import numpy
import scipy
import sympy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False
First, create a launcher icon (Adaptive and Legacy)
from Image Asset:
Select an image
for background layer and resize it to 0% or 1% and
In legacy tab set shape
to none
.
Then, delete folder res/mipmap/ic_laucher_round
in the project window and Open AndroidManifest.xml and remove attribute android:roundIcon="@mipmap/ic_launcher_round"
from the application
element.
In the end, delete ic_launcher.xml
from mipmap-anydpi-v26
.
Notice that: Some devices like Nexus 5X (Android 8.1) adding a white background automatically and can't do anything.
What good is a timestamp with its granularity given in seconds? I find it much more practical working with Time.now.to_f
. Heck, you may even throw a to_s.sub('.','')
to get rid of the decimal point, or perform a typecast like this: Integer(1e6*Time.now.to_f)
.
Access the field with array notation to avoid strict type checking on single field:
data['propertyName']; //will work even if data has not declared propertyName
Alternative way is (un)cast the variable for single access:
(<any>data).propertyName;//access propertyName like if data has no type
The first is shorter, the second is more explicit about type (un)casting
You can also totally disable type checking on all variable fields:
let untypedVariable:any= <any>{}; //disable type checking while declaring the variable
untypedVariable.propertyName = anyValue; //any field in untypedVariable is assignable and readable without type checking
Note: This would be more dangerous than avoid type checking just for a single field access, since all consecutive accesses on all fields are untyped
As mentioned by Alejandro Corredor it is a simple scope error. The subscribe
is run asynchronously and the open
must be placed in that context, so that the data finished loading when we trigger the download.
That said, there are two ways of doing it. As the docs recommend the service takes care of getting and mapping the data:
//On the service:
downloadfile(runname: string, type: string){
var headers = new Headers();
headers.append('responseType', 'arraybuffer');
return this.authHttp.get( this.files_api + this.title +"/"+ runname + "/?file="+ type)
.map(res => new Blob([res],{ type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }))
.catch(this.logAndPassOn);
}
Then, on the component we just subscribe and deal with the mapped data. There are two possibilities. The first, as suggested in the original post, but needs a small correction as noted by Alejandro:
//On the component
downloadfile(type: string){
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(data => window.open(window.URL.createObjectURL(data)),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
}
The second way would be to use FileReader. The logic is the same but we can explicitly wait for FileReader to load the data, avoiding the nesting, and solving the async problem.
//On the component using FileReader
downloadfile(type: string){
var reader = new FileReader();
this.pservice.downloadfile(this.rundata.name, type)
.subscribe(res => reader.readAsDataURL(res),
error => console.log("Error downloading the file."),
() => console.log('Completed file download.'));
reader.onloadend = function (e) {
window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no');
}
}
Note: I am trying to download an Excel file, and even though the download is triggered (so this answers the question), the file is corrupt. See the answer to this post for avoiding the corrupt file.
I think it should be
$('#fileinput').val();
One more option is WinRun4J. There is an Eclipse Plugin for WinRun4J that allows you to export your application as a single executable with necessary jars/classes embedded.
(full disclosure: I work on this project)
Simplyfing for the begginers:
If you want to select an element immediatly after another element you use the +
selector.
For example:
div + p
The "+" element selects all <p>
elements that are placed immediately after <div>
elements
If you want to learn more about selectors use this table
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:[email protected]
I know this is a late response but I was facing a similar issue and I managed to solve it by using notifyDataSetChanged()
in the right place.
So my situation was as follows.
I had to update a listview in an action bar tab (fragment) with contents returned from a completely different activity. Initially however, the listview would not reflect any changes. However, when I clicked another tab and then returned to the desired tab,the listview would be updated with the correct content from the other activity. So to solve this I used notifyDataSetChanged()
of the action bar adapter in the code of the activity which had to return the data.
This is the code snippet which I used in the activity.
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.action_new_forward:
FragmentTab2.mListAdapter.notifyDataSetChanged();//this updates the adapter in my action bar tab
Intent ina = new Intent(getApplicationContext(), MainActivity.class);
ina.putExtra("stra", values1);
startActivity(ina);// This is the code to start the parent activity of my action bar tab(fragment).
}
}
This activity would return some data to FragmentTab2
and it would directly update my listview in FragmentTab2
.
Hope someone finds this useful!
There are lots of solutions:
b = Arrays.copyOf(a, a.length);
Which allocates a new array, copies over the elements of a
, and returns the new array.
Or
b = new int[a.length];
System.arraycopy(a, 0, b, 0, b.length);
Which copies the source array content into a destination array that you allocate yourself.
Or
b = a.clone();
which works very much like Arrays.copyOf()
. See this thread.
Or the one you posted, if you reverse the direction of the assignment in the loop:
b[i] = a[i]; // NOT a[i] = b[i];
As noted in the previous answers somewhere the window.innerHeight variable gets updated properly now on iOS10 when the keyboard appears and since I don't need the support for earlier versions I came up with the following hack that might be a bit easier then the discussed "solutions".
//keep track of the "expected" height
var windowExpectedSize = window.innerHeight;
//update expected height on orientation change
window.addEventListener('orientationchange', function(){
//in case the virtual keyboard is open we close it first by removing focus from the input elements to get the proper "expected" size
if (window.innerHeight != windowExpectedSize){
$("input").blur();
$("div[contentEditable]").blur(); //you might need to add more editables here or you can focus something else and blur it to be sure
setTimeout(function(){
windowExpectedSize = window.innerHeight;
},100);
}else{
windowExpectedSize = window.innerHeight;
}
});
//and update the "expected" height on screen resize - funny thing is that this is still not triggered on iOS when the keyboard appears
window.addEventListener('resize', function(){
$("input").blur(); //as before you can add more blurs here or focus-blur something
windowExpectedSize = window.innerHeight;
});
then you can use:
if (window.innerHeight != windowExpectedSize){ ... }
to check if the keyboard is visible. I've been using it for a while now in my web app and it works well, but (as all of the other solutions) you might find a situation where it fails because the "expected" size is not updated properly or something.
The following worked out for me like a charm:
Tomcat can tell you in several ways. Here's the easiest:
$ /path/to/catalina.sh version
Using CATALINA_BASE: /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME: /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME: /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH: /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built: Jul 3 2012 11:31:52
Server number: 7.0.29.0
OS Name: Mac OS X
OS Version: 10.7.4
Architecture: x86_64
JVM Version: 1.6.0_33-b03-424-11M3720
JVM Vendor: Apple Inc.
If you don't know where catalina.sh
is (or it never gets called), you can usually find it via ps
:
$ ps aux | grep catalina
chris 930 0.0 3.1 2987336 258328 s000 S Wed01PM 2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start
From the ps
output, you can see both catalina.home
and catalina.base
. catalina.home
is where the Tomcat base files are installed, and catalina.base
is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.
You can also interrogate the JVM directly if you can't find it in a ps
listing:
$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29
If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home
and catalina.base
.
I got the answer for the same ,
Go on SQL Server ? Tools ? Options ? Designers ? Table and Database Designers
and unselect Prevent saving changes that require table re-creation
2- Open table design view and that scroll your column up and down and save your changes.
Using this answer from Asya Kamsky, I wrote a one-line bat script for Windows. The line looks like this:
mongo --quiet %1 --eval "printjson(db.%2.find().toArray())" > output.json
Then one can run it:
exportToJson.bat DbName CollectionName
On my side, i got this problem when i added a new project (Library)
How i solved it
Right click the new added Library go to Properties then Application, under Application change the Target Framework to the framework of all projects.
The problem is that you have project using different target frameworks.
it seems that you try to rename your master branch to Main. by using this command git branch -M Main where you were on master branch. execute this git command, il will work :
git push --all -u
after this you can run git branch
to see your branches
then you can delete the master branch like this :
git branch -D master
You cannot do that but you can do the opposite:
In your jsp you can:
String name = "John Allepe";
request.setAttribute("CustomerName", name);
Access the variable in the js:
var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);
This code is write on your form load. It display all the Tour in database when user type letter in combo box. This code automatically suggest and append the right choice as user want.
con.Open();
cmd = new SqlCommand("SELECT DISTINCT Tour FROM DetailsTB", con);
SqlDataReader sdr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(sdr);
combo_search2.DisplayMember = "Tour";
combo_search2.DroppedDown = true;
List<string> list = new List<string>();
foreach (DataRow row in dt.Rows)
{
list.Add(row.Field<string>("Tour"));
}
this.combo_search2.Items.AddRange(list.ToArray<string>());
combo_search2.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
combo_search2.AutoCompleteSource = AutoCompleteSource.ListItems;
con.Close();
I personally favour this syntax, which uses the explicit IsDbNull method exposed by IDataRecord
, and caches the column index to avoid a duplicate string lookup.
Expanded for readability, it goes something like:
int columnIndex = row.GetOrdinal("Foo");
string foo; // the variable we're assigning based on the column value.
if (row.IsDBNull(columnIndex)) {
foo = String.Empty; // or whatever
} else {
foo = row.GetString(columnIndex);
}
Rewritten to fit on a single line for compactness in DAL code - note that in this example we're assigning int bar = -1
if row["Bar"]
is null.
int i; // can be reused for every field.
string foo = (row.IsDBNull(i = row.GetOrdinal("Foo")) ? null : row.GetString(i));
int bar = (row.IsDbNull(i = row.GetOrdinal("Bar")) ? -1 : row.GetInt32(i));
The inline assignment can be confusing if you don't know it's there, but it keeps the entire operation on one line, which I think enhances readability when you're populating properties from multiple columns in one block of code.
Does the hash exist (with 0 as the value) or is it "put" to the map on the first increment? If it is "put" on the first increment, the code should look like:
if (hashmap.containsKey(key)) {
hashmap.put(key, hashmap.get(key)+1);
} else {
hashmap.put(key,1);
}
When you do new Promise((resolve)...
the type inferred was Promise<{}>
because you should have used new Promise<number>((resolve)
.
It is interesting that this issue was only highlighted when the async
keyword was added. I would recommend reporting this issue to the TS team on GitHub.
There are many ways you can get around this issue. All the following functions have the same behavior:
const whatever1 = () => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever2 = async () => {
return new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever3 = async () => {
return await new Promise<number>((resolve) => {
resolve(4);
});
};
const whatever4 = async () => {
return Promise.resolve(4);
};
const whatever5 = async () => {
return await Promise.resolve(4);
};
const whatever6 = async () => Promise.resolve(4);
const whatever7 = async () => await Promise.resolve(4);
In your IDE you will be able to see that the inferred type for all these functions is () => Promise<number>
.
Short answer: Use the change
event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.
Using querySelector
.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
} else {
console.log("Checkbox is not checked..");
}
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
$('input[name=checkbox]').change(function() {
if ($(this).is(':checked')) {
console.log("Checkbox is checked..")
} else {
console.log("Checkbox is not checked..")
}
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" />
_x000D_
Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll
instead of querySelector
. Then use Array.filter
and Array.map
to extract checked values.
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []
/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/
// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
enabledSettings =
Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
.filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
.map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
console.log(enabledSettings)
})
});
_x000D_
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
Short answer:
Use Delimiter='/'
. This avoids doing a recursive listing of your bucket. Some answers here wrongly suggest doing a full listing and using some string manipulation to retrieve the directory names. This could be horribly inefficient. Remember that S3 has virtually no limit on the number of objects a bucket can contain. So, imagine that, between bar/
and foo/
, you have a trillion objects: you would wait a very long time to get ['bar/', 'foo/']
.
Use Paginators
. For the same reason (S3 is an engineer's approximation of infinity), you must list through pages and avoid storing all the listing in memory. Instead, consider your "lister" as an iterator, and handle the stream it produces.
Use boto3.client
, not boto3.resource
. The resource
version doesn't seem to handle well the Delimiter
option. If you have a resource, say a bucket = boto3.resource('s3').Bucket(name)
, you can get the corresponding client with: bucket.meta.client
.
Long answer:
The following is an iterator that I use for simple buckets (no version handling).
import boto3
from collections import namedtuple
from operator import attrgetter
S3Obj = namedtuple('S3Obj', ['key', 'mtime', 'size', 'ETag'])
def s3list(bucket, path, start=None, end=None, recursive=True, list_dirs=True,
list_objs=True, limit=None):
"""
Iterator that lists a bucket's objects under path, (optionally) starting with
start and ending before end.
If recursive is False, then list only the "depth=0" items (dirs and objects).
If recursive is True, then list recursively all objects (no dirs).
Args:
bucket:
a boto3.resource('s3').Bucket().
path:
a directory in the bucket.
start:
optional: start key, inclusive (may be a relative path under path, or
absolute in the bucket)
end:
optional: stop key, exclusive (may be a relative path under path, or
absolute in the bucket)
recursive:
optional, default True. If True, lists only objects. If False, lists
only depth 0 "directories" and objects.
list_dirs:
optional, default True. Has no effect in recursive listing. On
non-recursive listing, if False, then directories are omitted.
list_objs:
optional, default True. If False, then directories are omitted.
limit:
optional. If specified, then lists at most this many items.
Returns:
an iterator of S3Obj.
Examples:
# set up
>>> s3 = boto3.resource('s3')
... bucket = s3.Bucket(name)
# iterate through all S3 objects under some dir
>>> for p in s3ls(bucket, 'some/dir'):
... print(p)
# iterate through up to 20 S3 objects under some dir, starting with foo_0010
>>> for p in s3ls(bucket, 'some/dir', limit=20, start='foo_0010'):
... print(p)
# non-recursive listing under some dir:
>>> for p in s3ls(bucket, 'some/dir', recursive=False):
... print(p)
# non-recursive listing under some dir, listing only dirs:
>>> for p in s3ls(bucket, 'some/dir', recursive=False, list_objs=False):
... print(p)
"""
kwargs = dict()
if start is not None:
if not start.startswith(path):
start = os.path.join(path, start)
# note: need to use a string just smaller than start, because
# the list_object API specifies that start is excluded (the first
# result is *after* start).
kwargs.update(Marker=__prev_str(start))
if end is not None:
if not end.startswith(path):
end = os.path.join(path, end)
if not recursive:
kwargs.update(Delimiter='/')
if not path.endswith('/'):
path += '/'
kwargs.update(Prefix=path)
if limit is not None:
kwargs.update(PaginationConfig={'MaxItems': limit})
paginator = bucket.meta.client.get_paginator('list_objects')
for resp in paginator.paginate(Bucket=bucket.name, **kwargs):
q = []
if 'CommonPrefixes' in resp and list_dirs:
q = [S3Obj(f['Prefix'], None, None, None) for f in resp['CommonPrefixes']]
if 'Contents' in resp and list_objs:
q += [S3Obj(f['Key'], f['LastModified'], f['Size'], f['ETag']) for f in resp['Contents']]
# note: even with sorted lists, it is faster to sort(a+b)
# than heapq.merge(a, b) at least up to 10K elements in each list
q = sorted(q, key=attrgetter('key'))
if limit is not None:
q = q[:limit]
limit -= len(q)
for p in q:
if end is not None and p.key >= end:
return
yield p
def __prev_str(s):
if len(s) == 0:
return s
s, c = s[:-1], ord(s[-1])
if c > 0:
s += chr(c - 1)
s += ''.join(['\u7FFF' for _ in range(10)])
return s
Test:
The following is helpful to test the behavior of the paginator
and list_objects
. It creates a number of dirs and files. Since the pages are up to 1000 entries, we use a multiple of that for dirs and files. dirs
contains only directories (each having one object). mixed
contains a mix of dirs and objects, with a ratio of 2 objects for each dir (plus one object under dir, of course; S3 stores only objects).
import concurrent
def genkeys(top='tmp/test', n=2000):
for k in range(n):
if k % 100 == 0:
print(k)
for name in [
os.path.join(top, 'dirs', f'{k:04d}_dir', 'foo'),
os.path.join(top, 'mixed', f'{k:04d}_dir', 'foo'),
os.path.join(top, 'mixed', f'{k:04d}_foo_a'),
os.path.join(top, 'mixed', f'{k:04d}_foo_b'),
]:
yield name
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
executor.map(lambda name: bucket.put_object(Key=name, Body='hi\n'.encode()), genkeys())
The resulting structure is:
./dirs/0000_dir/foo
./dirs/0001_dir/foo
./dirs/0002_dir/foo
...
./dirs/1999_dir/foo
./mixed/0000_dir/foo
./mixed/0000_foo_a
./mixed/0000_foo_b
./mixed/0001_dir/foo
./mixed/0001_foo_a
./mixed/0001_foo_b
./mixed/0002_dir/foo
./mixed/0002_foo_a
./mixed/0002_foo_b
...
./mixed/1999_dir/foo
./mixed/1999_foo_a
./mixed/1999_foo_b
With a little bit of doctoring of the code given above for s3list
to inspect the responses from the paginator
, you can observe some fun facts:
The Marker
is really exclusive. Given Marker=topdir + 'mixed/0500_foo_a'
will make the listing start after that key (as per the AmazonS3 API), i.e., with .../mixed/0500_foo_b
. That's the reason for __prev_str()
.
Using Delimiter
, when listing mixed/
, each response from the paginator
contains 666 keys and 334 common prefixes. It's pretty good at not building enormous responses.
By contrast, when listing dirs/
, each response from the paginator
contains 1000 common prefixes (and no keys).
Passing a limit in the form of PaginationConfig={'MaxItems': limit}
limits only the number of keys, not the common prefixes. We deal with that by further truncating the stream of our iterator.
The accepted answer is one way of fixing the issue, because it will just apply some strategy for the problematic dependency (com.google.code.findbugs:jsr305) and it will resolve the problem around the project, using some version of this dependency. Basically it will align the versions of this library inside the whole project.
There is an answer from @Santhosh (and couple of other people) who suggests to exclude the same dependency for espresso, which should work by the same way, but if the project has some other dependencies who depend on the same library (com.google.code.findbugs:jsr305), again we will have the same issue. So in order to use this approach you will need to exclude the same group from all project dependencies, who depend on com.google.code.findbugs:jsr305. I personally found that Espresso Contrib and Espresso Intents also use com.google.code.findbugs:jsr305.
I hope this thoughts will help somebody to realise what exactly is happening here and how things work (not just copy paste some code) :).
Well I am bit late to answer,but my code is tested
check scheme from uri:
byte[] videoBytes;
if (uri.getScheme().equals("content")){
InputStream iStream = context.getContentResolver().openInputStream(uri);
videoBytes = getBytes(iStream);
}else{
File file = new File(uri.getPath());
FileInputStream fileInputStream = new FileInputStream(file);
videoBytes = getBytes(fileInputStream);
}
In the above answer I converted the video uri to bytes array , but that's not related to question,
I just copied my full code to show the usage of FileInputStream
and InputStream
as both are working same in my code.
I used the variable context which is getActivity() in my Fragment and in Activity it simply be ActivityName.this
context=getActivity();
//in Fragment
context=ActivityName.this;
// in activity
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
// Path relative to where the php file is or absolute server path
chdir($FilePath); // Comment this out if you are on the same folder
chown($FileName,465); //Insert an Invalid UserId to set to Nobody Owner; for instance 465
$do = unlink($FileName);
if($do=="1"){
echo "The file was deleted successfully.";
} else { echo "There was an error trying to delete the file."; }
Try this. Hope it helps.
Stripping things down to basics this is what you would want to test with:
import socket
server = socket.socket()
server.bind(("10.0.0.1", 6677))
server.listen(4)
client_socket, client_address = server.accept()
print(client_address, "has connected")
while 1==1:
recvieved_data = client_socket.recv(1024)
print(recvieved_data)
This works assuming a few things:
Try the following, open the start menu, in the "search" field type cmd
and press enter.
Once the black console opens up type ping www.google.com
and this should give you and IP address for google. This address is googles local IP and they bind to that and obviously you can not bind to an IP address owned by google.
With that in mind, you own your own set of IP addresses.
First you have the local IP of the server, but then you have the local IP of your house.
In the below picture 192.168.1.50
is the local IP of the server which you can bind to.
You still own 83.55.102.40
but the problem is that it's owned by the Router and not your server. So even if you visit http://whatsmyip.com and that tells you that your IP is 83.55.102.40
that is not the case because it can only see where you're coming from.. and you're accessing your internet from a router.
In order for your friends to access your server (which is bound to 192.168.1.50
) you need to forward port 6677
to 192.168.1.50
and this is done in your router.
Assuming you are behind one.
If you're in school there's other dilemmas and routers in the way most likely.
andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.
I wrote an in-depth blog post about this that you can check out here:
https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/
Try this code to 100% work....
UIImageView * imageview = [[UIImageView alloc] initWithFrame:CGRectMake(20,100, 80, 80)];
imageview.image = [UIImage imageNamed:@"myimage.jpg"];
[self.view addSubview:imageview];
I had same issues, edited my hosts file 127.0.0.1 localhost, but noticed no difference.
I then disabled Compression in the IIS panel and applied, and problem appears to now be resolved.
IIS Manager > Compression > Uncheck 'Enable dynamic content compression' and uncheck 'Enable static content compression'. Then 'Apply'.
Hope this helps!
regards, Geoff
For CLI C++ (compiled with /clr) see this MSDN link.
In short, a property can be given the name "default":
ref class Class
{
public:
property System::String^ default[int i]
{
System::String^ get(int i) { return "hello world"; }
}
};
Laravel 5:
return redirect(...)->withInput();
for back only:
return back()->withInput();
I can recommend add small extension to String or Array that looks like
extension Collection {
public var isNotEmpty: Bool {
return !self.isEmpty
}
}
With it you can write code that is easier to read. Compare this two lines
if !someObject.someParam.someSubParam.someString.isEmpty {}
and
if someObject.someParam.someSubParam.someString.isNotEmpty {}
It is easy to miss ! sign in the beginning of fist line.
use - !important - to override default black
.fa-heart:hover{_x000D_
color:red !important;_x000D_
}_x000D_
.fa-heart-o:hover{_x000D_
color:red !important;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
<i class="fa fa-heart fa-2x"></i>_x000D_
<i class="fa fa-heart-o fa-2x"></i>
_x000D_
To reset the styles defined for legend
in bootstrap, you can do following in your css file:
legend {
all: unset;
}
Ref: https://css-tricks.com/almanac/properties/a/all/
The all property in CSS resets all of the selected element's properties, except the direction and unicode-bidi properties that control text direction.
Possible values are: initial
, inherit
& unset
.
Side note: clear
property is used in relation with float
(https://css-tricks.com/almanac/properties/c/clear/)
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
From VS:
From VS on a different machine
You don't need VS to be on the same machine as the enlistment as you can edit remote enlistments! In the dialog that comes up when you press the "Workspaces..." item there is a check box stating "Show Remote Workspaces" - just tick that and you'll get a list of all your enlistments:
From the command line
Call "tf workspace" from a developer command prompt. It will bring up the "Manage Workspaces" directly!
Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);
Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);
float distanceInMeters = loc1.distanceTo(loc2);
You must specify your file in the copy:
xcopy C:\source\myfile.txt C:\target
Or if you want to copy all txt files for example
xcopy C:\source\*.txt C:\target
I just had this problem. Turns out the XML file (not the contents) was not encoded in utf-8, but in ISO-8859-1. You can check this on a Mac with file -I xml_filename
.
I used Sublime to change the file encoding to utf-8, and lxml imported it no issues.
Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html
Then add a button or something on the form and inside its event, just open this app ie:
{
Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");
}
Since Python 3.7 and no external libraries, you can use the strptime function from the datetime module:
datetime.datetime.strptime('2019-01-04T16:41:24+0200', "%Y-%m-%dT%H:%M:%S%z")
For more formatting options, see here.
Python 2 doesn't support the %z
format specifier, so it's best to explicitly use Zulu time everywhere if possible:
datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")
You could query the sys.tables database view to get out the names of the tables, and then use this query to build yourself another query to do the update on the back of that. For instance:
select 'select * from '+name from sys.tables
will give you a script that will run a select * against all the tables in the system catalog, you could alter the string in the select clause to do your update, as long as you know the column name is the same on all the tables you wish to update, so your script would look something like:
select 'update '+name+' set comments = ''(*)''+comments where comments like ''%comment to be updated%'' ' from sys.tables
You could also then predicate on the tables query to only include tables that have a name in a certain format, or are in a subset you want to create the update script for.
I know there's a lot of answers here, but they all seem a bit confusing. So after doing some research from the Java oracle study guide, I've come up with three different scenarios of when to use && or &. The three scenarios are logical AND, bitwise AND, and boolean AND.
Logical AND:
Logical AND (aka Conditional AND) uses the && operator. It's short-circuited meaning: if the left operand is false, then the right operand will not be evaluated.
Example:
int x = 0;
if (false && (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); // "0"
In the above example the value printed to the console of x will be 0, because the first operand in the if statement is false, hence java has no need to compute (1 == ++x) therefore x will not be computed.
Bitwise AND: Bitwise AND uses the & operator. It's used to preform a bitwise operation on the value. It's much easier to see what's going on by looking at operation on binary numbers ex:
int a = 5; // 5 in binary is 0101
int b = 12; // 12 in binary is 1100
int c = a & b; // bitwise & preformed on a and b is 0100 which is 4
As you can see in the example, when the binary representations of the numbers 5 and 12 are lined up, then a bitwise AND preformed will only produce a binary number where the same digit in both numbers have a 1. Hence 0101 & 1100 == 0100. Which in decimal is 5 & 12 == 4.
Boolean AND: Now the boolean AND operator behaves similarly and differently to both the bitwise AND and logical AND. I like to think of it as preforming a bitwise AND between two boolean values (or bits), therefore it uses & operator. The boolean values can be the result of a logical expression too.
It returns either a true or false value, much like the logical AND, but unlike the logical AND it is not short-circuited. The reason being, is that for it to preform that bitwise AND, it must know the value of both left and right operands. Here's an ex:
int x = 0;
if (false & (1 == ++x) {
System.out.println("Inside of if");
}
System.out.println(x); //"1"
Now when that if statement is ran, the expression (1 == ++x) will be executed, even though the left operand is false. Hence the value printed out for x will be 1 because it got incremented.
This also applies to Logical OR (||), bitwise OR (|), and boolean OR (|) Hope this clears up some confusion.
This what I did to show the confirmation message just when I have unsaved data
window.onbeforeunload = function () {
if (isDirty) {
return "There are unsaved data.";
}
return undefined;
}
returning "undefined" will disable the confirmation
Note: returning "null" will not work with IE
Also you can use "undefined" to disable the confirmation
window.onbeforeunload = undefined;
list(cursor)
works because a cursor is an iterable; you can also use cursor
in a loop:
for row in cursor:
# ...
A good database adapter implementation will fetch rows in batches from the server, saving on the memory footprint required as it will not need to hold the full result set in memory. cursor.fetchall()
has to return the full list instead.
There is little point in using list(cursor)
over cursor.fetchall()
; the end effect is then indeed the same, but you wasted an opportunity to stream results instead.
Smoke tests are tests which aim is to check if everything was build correctly. I mean here integration, connections. So you check from technically point of view if you can make wider tests. You have to execute some test cases and check if the results are positive.
Sanity tests in general have the same aim - check if we can make further test. But in sanity test you focus on business value so you execute some test cases but you check the logic.
In general people say smoke tests for both above because they are executed in the same time (sanity after smoke tests) and their aim is similar.
Try this:
function someFunction(username, password) {
return new Promise((resolve, reject) => {
// Do something with the params username and password...
if ( /* everything turned out fine */ ) {
resolve("Stuff worked!");
} else {
reject(Error("It didn't work!"));
}
});
}
someFunction(username, password)
.then((result) => {
// Do something...
})
.catch((err) => {
// Handle the error...
});
You could do this but it is hacky
.application-title {
background:url("/path/to/image.png");
/* set these dims according to your image size */
width:500px;
height:500px;
}
.application-title img {
display:none;
}
Here is a working example:
If you don't want to store table in database then @Evan Todd already has been provided temporary table solution.
But if you need that table for other users and want to store in db then you can use below procedure.
Create below ‘stored procedure’:
————————————
DELIMITER $$
USE `test`$$
DROP PROCEDURE IF EXISTS `sp_variable_table`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_variable_table`()
BEGIN
SELECT CONCAT(‘zafar_’,REPLACE(TIME(NOW()),’:',’_')) INTO @tbl;
SET @str=CONCAT(“create table “,@tbl,” (pbirfnum BIGINT(20) NOT NULL DEFAULT ’0', paymentModes TEXT ,paymentmodeDetails TEXT ,shippingCharges TEXT ,shippingDetails TEXT ,hypenedSkuCodes TEXT ,skuCodes TEXT ,itemDetails TEXT ,colorDesc TEXT ,size TEXT ,atmDesc TEXT ,promotional TEXT ,productSeqNumber VARCHAR(16) DEFAULT NULL,entity TEXT ,entityDetails TEXT ,kmtnmt TEXT ,rating BIGINT(1) DEFAULT NULL,discount DECIMAL(15,0) DEFAULT NULL,itemStockDetails VARCHAR(38) NOT NULL DEFAULT ”) ENGINE=INNODB DEFAULT CHARSET=utf8");
PREPARE stmt FROM @str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SELECT ‘Table has been created’;
END$$
DELIMITER ;
———————————————–
Now you can execute this procedure to create a variable name table as per below-
call sp_variable_table();
You can check new table after executing below command-
use test;show tables like ‘%zafar%’; — test is here ‘database’ name.
You can also check more details at below path-
http://mydbsolutions.in/how-can-create-a-table-with-variable-name/
pylab
, not matplotlib.pyplot
You may try using hist
to put your data info along with the fitted curve as below:
import numpy as np
import scipy.stats as stats
import pylab as pl
h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]) #sorted
fit = stats.norm.pdf(h, np.mean(h), np.std(h)) #this is a fitting indeed
pl.plot(h,fit,'-o')
pl.hist(h,normed=True) #use this to draw histogram of your data
pl.show() #use may also need add this
you can use crypto-js javaScript library of crypto standards, there is easiest way to generate sha256
or sha512
const SHA256 = require("crypto-js/sha256");
const SHA512 = require("crypto-js/sha512");
let password = "hello"
let hash_256 = SHA256 (password).toString();
let hash_512 = SHA512 (password).toString();
You can see in this List of useful HTTP headers.
X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.
I can also propose following solution for C++11.
for (auto p = 0U; p < sys.size(); p++) {
}
(C++ is not smart enough for auto p = 0, so I have to put p = 0U....)
Imagine it this way: a mail truck can carry 5000 sheets of paper each trip so It's bandwidth is 5000. Does that mean it can carry 5000 letter each trip? Well, theoretically, if each letter didn't need an envelope telling us where it was coming from, going too, and possessing proof of payment (Envelope = Protocol Headers and Footers). But they do, so each letter (1 sheet of paper) requires an envelope (= to about 1 sheet of paper) to get it to it's destination. So in the worst case scenario (all envelopes only have one page letters), the truck would carry only 2500 sheets Throughput (Data that we want to send from source>destination, THE LETTERS) and would have 2500 sheets Overhead (Headers/Footer that we need to get the letter from source>destination but that the recipient won't be reading, THE ENVELOPES). The Throughput, 2500 Letters + the Overhead, 2500 Envelopes = Bandwidth, 5000 sheets of paper. Bigger letters (4 pages) still only require 1 envelope so that would move the ratio of Throughput to Overhead higher (i.e. Jumbo Frames) and make it more efficient, so if all the letters were 4 page letters throughput would change to 4000, and overhead would reduce to 1000, together equaling the 5000 Bandwidth of the truck.