I want to correct little bit the above code
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, mToolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close
);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
and all the other things will remain same...
For those who are having problem Drawerlayout
overlaying toolbar
add android:layout_marginTop="?attr/actionBarSize"
to root layout of drawer content
Please check that you are running the android device over same network. This will solve the problem. have fun!!!
Try this
$(".answer").hide();
$(".coupon_question").click(function() {
if($(this).is(":checked")) {
$(".answer").show(300);
} else {
$(".answer").hide(200);
}
});
C++17 introduced std::basic_string_view
, a class template that refers to a constant contiguous sequence of char-like objects, i.e. a view of the string. Apart from having a very similar interface to std::basic_string
, it has two additional functions: remove_prefix()
, which shrinks the view by moving its start forward; and
remove_suffix()
, which shrinks the view by moving its end backward. These can be used to trim leading and trailing space:
#include <string_view>
#include <string>
std::string_view ltrim(std::string_view str)
{
const auto pos(str.find_first_not_of(" \t"));
str.remove_prefix(pos);
return str;
}
std::string_view rtrim(std::string_view str)
{
const auto pos(str.find_last_not_of(" \t"));
str.remove_suffix(str.length() - pos - 1);
return str;
}
std::string_view trim(std::string_view str)
{
str = ltrim(str);
str = rtrim(str);
return str;
}
int main()
{
std::string str = " hello world ";
auto sv1{ ltrim(str) }; // "hello world "
auto sv2{ rtrim(str) }; // " hello world"
auto sv3{ trim(str) }; // "hello world"
//If you want, you can create std::string objects from std::string_view objects
auto s1{ sv1 };
auto s2{ sv2 };
auto s3{ sv3 };
}
Note: the std::string_view
is a non-owning reference, so it's only valid as long as the original string still exists.
A lock should be considered to use, such as threading.Lock
. See lock-objects for more info.
The accepted answer CAN print 10 by thread1, which is not what you want. You can run the following code to understand the bug more easily.
def thread1(threadname):
while True:
if a % 2 and not a % 2:
print "unreachable."
def thread2(threadname):
global a
while True:
a += 1
Using a lock can forbid changing of a
while reading more than one time:
def thread1(threadname):
while True:
lock_a.acquire()
if a % 2 and not a % 2:
print "unreachable."
lock_a.release()
def thread2(threadname):
global a
while True:
lock_a.acquire()
a += 1
lock_a.release()
If thread using the variable for long time, coping it to a local variable first is a good choice.
You just need to put the file path (directory) before the name of the image. Example:
fig.savefig('/home/user/Documents/graph.png')
Other example:
fig.savefig('/home/user/Downloads/MyImage.png')
As a workaround, go to sdk installation directory and perform the following steps:
system-images/android-19/default
system-images/android-19/
The directory structure should look like this:
And it should work!
Building slightly upon the answers here, I've wrapped this process up as a simple Bash script, which could of course be used as a Git alias as well.
The important addition to me is that this prompts me to run unit tests before committing and passes in the current branch name by default.
$ git_push_new_branch.sh
Have you run your unit tests yet? If so, pass OK or a branch name, and try again
usage: git_push_new_branch {OK|BRANCH_NAME}
e.g.
git_push_new_branch -> Displays prompt reminding you to run unit tests
git_push_new_branch OK -> Pushes the current branch as a new branch to the origin
git_push_new_branch MYBRANCH -> Pushes branch MYBRANCH as a new branch to the origin
function show_help()
{
IT=$(cat <<EOF
Have you run your unit tests yet? If so, pass OK or a branch name, and try again
usage: git_push_new_branch {OK|BRANCH_NAME}
e.g.
git_push_new_branch.sh -> Displays prompt reminding you to run unit tests
git_push_new_branch.sh OK -> Pushes the current branch as a new branch to the origin
git_push_new_branch.sh MYBRANCH -> Pushes branch MYBRANCH as a new branch to the origin
)
echo "$IT"
exit
}
if [ -z "$1" ]
then
show_help
fi
CURR_BRANCH=$(git rev-parse --abbrev-ref HEAD)
if [ "$1" == "OK" ]
then
BRANCH=$CURR_BRANCH
else
BRANCH=${1:-$CURR_BRANCH}
fi
git push -u origin $BRANCH
Try this code
if ($(window).width() < 960) {
alert('width is less than 960px');
}
else {
alert('More than 960');
}
if ($(window).width() < 960) {_x000D_
alert('width is less than 960px');_x000D_
}_x000D_
else {_x000D_
alert('More than 960');_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
Dim: you are defining a variable (here: r is a variable of type Range)
Set: you are setting the property (here: set the value of r to Range("A1") - this is not a type, but a value).
You have to use set with objects, if r were a simple type (e.g. int, string), then you would just write:
Dim r As Integer
r=5
In the latest version of iOS this method is now deprecated. To support both iOS 7 and iOS 8 use:
UIApplication *application = [UIApplication sharedApplication];
BOOL enabled;
// Try to use the newer isRegisteredForRemoteNotifications otherwise use the enabledRemoteNotificationTypes.
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
enabled = [application isRegisteredForRemoteNotifications];
}
else
{
UIRemoteNotificationType types = [application enabledRemoteNotificationTypes];
enabled = types & UIRemoteNotificationTypeAlert;
}
Here is the codepen demo showing the solution:
Important highlights:
html
, body
, ... .container
, should have the height set to 100%flex
to ANY of the flex items will trigger calculation of the items sizes based on flex distribution:
flex
, for example: flex: 1
then this flex item will occupy the remaining of the spaceflex
property, the calculation will be more complicated. For example, if the item 1 is set to flex: 1
and the item 2 is se to flex: 2
then the item 2 will take twice more of the remaining space
flex-direction
propertyflex
property: https://www.w3.org/TR/css-flexbox-1/#propdef-flex
min-*
and max-*
will be respectedIn C, memcpy is only foolishly risky. As long as you get all three parameters exactly right, none of the struct members are pointers (or, you explicitly intend to do a shallow copy) and there aren't large alignment gaps in the struct that memcpy is going to waste time looping through (or performance never matters), then by all means, memcpy. You gain nothing except code that is harder to read, fragile to future changes and has to be hand-verified in code reviews (because the compiler can't), but hey yeah sure why not.
In C++, we advance to the ludicrously risky. You may have members of types which are not safely memcpyable, like std::string, which will cause your receiving struct to become a dangerous weapon, randomly corrupting memory whenever used. You may get surprises involving virtual functions when emulating slice-copies. The optimizer, which can do wondrous things for you because it has a guarantee of full type knowledge when it compiles =, can do nothing for your memcpy call.
In C++ there's a rule of thumb - if you see memcpy or memset, something's wrong. There are rare cases when this is not true, but they do not involve structs. You use memcpy when, and only when, you have reason to blindly copy bytes.
Assignment on the other hand is simple to read, checks correctness at compile time and then intelligently moves values at runtime. There is no downside.
brew install python3
create alias in your shell profile
alias pip3="python3 -m pip"
in my .zshrc
? ~ pip3 --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)
Where is this info kept ("this connection is between computer
A
and serverF
")?
A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.
HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.
This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.
When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection
No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.
which is only for my session ?
Does it mean that no one else can use that connection
That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.
If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?
Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:
if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)
An typical keep-alive response looks like this:
Keep-Alive: timeout=15, max=100
See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):
A host sets the value of the timeout
parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.
The max
parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.
However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.
For images, open an image in google viewer. i.e.
https://docs.google.com/file/d/0Bz7qe_olclTwWDNJRDRmb1pJamM/edit
then view source> find word "texmex-thumb" and aside it there will be link.
Assembly code is a human readable representation of machine code:
mov eax, 77
jmp anywhere
Machine code is pure hexadecimal code:
5F 3A E3 F1
I assume you mean object code as in an object file. This is a variant of machine code, with a difference that the jumps are sort of parameterized such that a linker can fill them in.
An assembler is used to convert assembly code into machine code (object code) A linker links several object (and library) files to generate an executable.
I have once written an assembler program in pure hex (no assembler available) luckily this was way back on the good old (ancient) 6502. But I'm glad there are assemblers for the pentium opcodes.
Try this
<allow users="?" />
Now you are using <deny users="?" />
that means you are not allowing authenticated user to use your site.
If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40)
.
If you use pyplot
programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40)
or afterwards with ax.yaxis.label.set_size(40)
.
var empty = $("#cartContent").html().trim().length == 0;
docker start `docker ps -a | awk '{print $1}'`
This will start up all the containers that are in the 'Exited' state
try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}
But still I am not sure how it works?
Let's say an entity MyEntity
has an annotated version
property:
@Entity
public class MyEntity implements Serializable {
@Id
@GeneratedValue
private Long id;
private String name;
@Version
private Long version;
//...
}
On update, the field annotated with @Version
will be incremented and added to the WHERE
clause, something like this:
UPDATE MYENTITY SET ..., VERSION = VERSION + 1 WHERE ((ID = ?) AND (VERSION = ?))
If the WHERE
clause fails to match a record (because the same entity has already been updated by another thread), then the persistence provider will throw an OptimisticLockException
.
Does it mean that we should declare our version field as final
No but you could consider making the setter protected as you're not supposed to call it.
Try this:
import os
import shutil
for file in os.listdir(dirpath):
newfile = os.path.join(dirpath, file.split("_",1)[1])
shutil.move(os.path.join(dirpath,file),newfile)
I'm assuming you don't want to remove the file extension, but you can just do the same split with periods.
Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method
using System;
using System.IO.Ports;
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this
SerialPortProgram();
}
private static void SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Console.ReadLine();
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
Or is you want to do it based on what you were trying to do , you can try this
public class MySerialReader : IDisposable
{
private SerialPort serialPort;
private Queue<byte> recievedData = new Queue<byte>();
public MySerialReader()
{
serialPort = new SerialPort();
serialPort.Open();
serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
data.ToList().ForEach(b => recievedData.Enqueue(b));
processData();
}
void processData()
{
// Determine if we have a "packet" in the queue
if (recievedData.Count > 50)
{
var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
}
}
public void Dispose()
{
if (serialPort != null)
{
serialPort.Dispose();
}
}
I have two recommendation for you
-Drevision=2.0.1
in .mvn/maven.config
file. So basically you define your version only at one location.You can use -webkit-border-radius: 0;
. Like this:-
-webkit-border-radius: 0;
border: 0;
outline: 1px solid grey;
outline-offset: -1px;
This will give square corners as well as dropdown arrows. Using -webkit-appearance: none;
is not recommended as it will turn off all the styling done by Chrome.
You can just write something quickly yourself:
public static class Extensions
{
public static string ToCSV(this DataTable table)
{
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
}
And to test:
public static void Main()
{
DataTable table = new DataTable();
table.Columns.Add("Name");
table.Columns.Add("Age");
table.Rows.Add("John Doe", "45");
table.Rows.Add("Jane Doe", "35");
table.Rows.Add("Jack Doe", "27");
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(table.ToCSV());
MemoryStream stream = new MemoryStream(bytes);
StreamReader reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
}
EDIT: Re your comments:
It depends on how you want your csv formatted but generally if the text contains special characters, you want to enclose it in double quotes ie: "my,text". You can add checking in the code that creates the csv to check for special characters and encloses the text in double quotes if it is. As for the .NET 2.0 thing, just create it as a helper method in your class or remove the word this in the method declaration and call it like so : Extensions.ToCsv(table);
To check with current branch:
git diff -- projects/components/some.component.ts ... origin
git diff -- projects/components/some.component.html ... origin
To check with some other branch say staging:
git diff -- projects/components/some.component.ts ... origin/staging
git diff -- projects/components/some.component.html ... origin/staging
Anaconda does not use the PYTHONPATH
. One should however note that if the PYTHONPATH
is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a
unset PYTHONPATH
For instance this PYTHONPATH points to an incorrect pandas lib:
export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
unsetting the PYTHONPATH
prevents the wrong pandas lib from being loaded:
unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>
I found that the WebClient kept removing my User-Agent header after one request and I was tired of setting it each time. I used a hack to set the User-Agent permanently by making my own custom WebClient and overriding the GetWebRequest method. Hope this helps.
public class CustomWebClient : WebClient
{
public CustomWebClient(){}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address) as HttpWebRequest;
request.UserAgent="Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/6.0;)";
//... your other custom code...
return request;
}
}
Maybe you need "sys." before:
select * from sys.registry$history;
I think this will help
<directoryBrowse enabled="false" />
<defaultDocument>
<files>
<clear />
<add value="index.aspx" />
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
<add value="default.aspx" />
<add value="index.php" />
</files>
</defaultDocument>
</system.webServer>
Here is a great one http://download.oracle.com/javase/1.5.0/docs/api/
These languages are big. You cant expect a cheat sheet to fit on a piece of paper
I had the same problem recently.
First you need to install HAXM in the Android SDK Manager (from the error message I think you already did that). This will enable the emulator to use the HAXM framework, and for this it needs to open the HAX device. On your system this cannot be found, hence the error message.
To make this device available, you need to install the HAXM driver from Intel. You can find it here: http://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager (You also need to enable virtualization in your computer BIOS).
Hope this helps.
you can close it programmatically by calling
$('#form-dialog').dialog('close')
whenever you want.
If you want to kill the process(es) or cmd.exe carrying a particular title(s).
import csv, os
import subprocess
# ## Find the command prompt windows.
# ## Collect the details of the command prompt windows and assign them.
tasks = csv.DictReader(subprocess.check_output('tasklist /fi "imagename eq cmd.exe" /v /fo csv').splitlines(), delimiter=',', quotechar='"')
# ## The cmds with titles to be closed.
titles= ["Ploter", "scanFolder"]
# ## Find the PIDs of the cmds with the above titles.
PIDList = []
for line in tasks:
for title in titles:
if title in line['Window Title']:
print line['Window Title']
PIDList.append(line['PID'])
# ## Kill the CMDs carrying the PIDs in PIDList
for id in PIDList:
os.system('taskkill /pid ' + id )
Hope it helps. Their might be numerous better solutions to mine.
You can try it out http://api.jquery.com/mouseover/ on the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.
In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from the parent element to the element.
I found DataTables to be quite flexible. While its default version is based on jquery, there is also an AngularJs plugin.
One approach to achieve this would be like this
$new = [
[
'hashtag' => 'a7e87329b5eab8578f4f1098a152d6f4',
'title' => 'Flower',
'order' => 3,
],
[
'hashtag' => 'b24ce0cd392a5b0b8dedc66c25213594',
'title' => 'Free',
'order' => 2,
],
[
'hashtag' => 'e7d31fc0602fb2ede144d18cdffd816b',
'title' => 'Ready',
'order' => 1,
],
];
$keys = array_column($new, 'order');
array_multisort($keys, SORT_ASC, $new);
var_dump($new);
Result:
Array
(
[0] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)
[2] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)
)
For SDK 29 :
String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}
public static void createTextFile(String sBody, String FileName, String Where) {
try {
File gpxfile = new File(Where, FileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Then you can save your file like this :
createTextFile("This is Content","file.txt",str1);
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
You have an instance method called num_words
, but you also have a variable called num_words
. They have the same name. When you run num_words()
, the function replaces itself with its own output, which probably isn't what you want to do. Consider return
ing your values.
To fix your problem, change def num_words
to something like def get_num_words
and your code should work fine. Also, change print test.sort_word_list
to print test.sorted_word_list
.
ExecuteScalar()
is what you need here
Referring to Gamaliel 's answer: $args is an array of the arguments that are passed into a script at runtime - as such cannot be used the way Gamaliel is using it. This is actually working:
$myPath = 'C:\whatever.file'
# get actual Acl entry
$myAcl = Get-Acl "$myPath"
$myAclEntry = "Domain\User","FullControl","Allow"
$myAccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($myAclEntry)
# prepare new Acl
$myAcl.SetAccessRule($myAccessRule)
$myAcl | Set-Acl "$MyPath"
# check if added entry present
Get-Acl "$myPath" | fl
Update for PHP 7 (thanks shock_gone_wild)
PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:
$var = $var ?? "default";
Before PHP 7
No, there is no special operator or special syntax for this. However, you could use the ternary operator:
$var = isset($var) ? $var : "default";
Or like this:
isset($var) ?: $var = 'default';
From http://matplotlib.sourceforge.net/examples/event_handling/pick_event_demo.html :
from matplotlib.pyplot import figure, show
import numpy as npy
from numpy.random import rand
if 1: # picking on a scatter plot (matplotlib.collections.RegularPolyCollection)
x, y, c, s = rand(4, 100)
def onpick3(event):
ind = event.ind
print('onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind))
fig = figure()
ax1 = fig.add_subplot(111)
col = ax1.scatter(x, y, 100*s, c, picker=True)
#fig.savefig('pscoll.eps')
fig.canvas.mpl_connect('pick_event', onpick3)
show()
TRY
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings
EnableAutoProxyResultCache = dword: 0
50 - List1[0][0] + List[0][1] - List[0][2]
List[0]
gives you the first list in the list (try out print List[0]
). Then, you index into it again to get the items of that list. Think of it this way: (List1[0])[0]
.
Apart from the other already mentioned valid use cases std::weak_ptr
is an awesome tool in a multithreaded environment, because
std::shared_ptr
in conjunction with std::weak_ptr
is safe against dangling pointers - in opposite to std::unique_ptr
in conjunction with raw pointers std::weak_ptr::lock()
is an atomic operation (see also About thread-safety of weak_ptr)Consider a task to load all images of a directory (~10.000) simultaneously into memory (e.g. as a thumbnail cache). Obviously the best way to do this is a control thread, which handles and manages the images, and multiple worker threads, which load the images. Now this is an easy task. Here's a very simplified implementation (join()
etc is omitted, the threads would have to be handled differently in a real implementation etc)
// a simplified class to hold the thumbnail and data
struct ImageData {
std::string path;
std::unique_ptr<YourFavoriteImageLibData> image;
};
// a simplified reader fn
void read( std::vector<std::shared_ptr<ImageData>> imagesToLoad ) {
for( auto& imageData : imagesToLoad )
imageData->image = YourFavoriteImageLib::load( imageData->path );
}
// a simplified manager
class Manager {
std::vector<std::shared_ptr<ImageData>> m_imageDatas;
std::vector<std::unique_ptr<std::thread>> m_threads;
public:
void load( const std::string& folderPath ) {
std::vector<std::string> imagePaths = readFolder( folderPath );
m_imageDatas = createImageDatas( imagePaths );
const unsigned numThreads = std::thread::hardware_concurrency();
std::vector<std::vector<std::shared_ptr<ImageData>>> splitDatas =
splitImageDatas( m_imageDatas, numThreads );
for( auto& dataRangeToLoad : splitDatas )
m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
}
};
But it becomes much more complicated, if you want to interrupt the loading of the images, e.g. because the user has chosen a different directory. Or even if you want to destroy the manager.
You'd need thread communication and have to stop all loader threads, before you may change your m_imageDatas
field. Otherwise the loaders would carry on loading until all images are done - even if they are already obsolete. In the simplified example, that wouldn't be too hard, but in a real environment things can be much more complicated.
The threads would probably be part of a thread pool used by multiple managers, of which some are being stopped, and some aren't etc. The simple parameter imagesToLoad
would be a locked queue, into which those managers push their image requests from different control threads with the readers popping the requests - in an arbitrary order - at the other end. And so the communication becomes difficult, slow and error-prone. A very elegant way to avoid any additional communication in such cases is to use std::shared_ptr
in conjunction with std::weak_ptr
.
// a simplified reader fn
void read( std::vector<std::weak_ptr<ImageData>> imagesToLoad ) {
for( auto& imageDataWeak : imagesToLoad ) {
std::shared_ptr<ImageData> imageData = imageDataWeak.lock();
if( !imageData )
continue;
imageData->image = YourFavoriteImageLib::load( imageData->path );
}
}
// a simplified manager
class Manager {
std::vector<std::shared_ptr<ImageData>> m_imageDatas;
std::vector<std::unique_ptr<std::thread>> m_threads;
public:
void load( const std::string& folderPath ) {
std::vector<std::string> imagePaths = readFolder( folderPath );
m_imageDatas = createImageDatas( imagePaths );
const unsigned numThreads = std::thread::hardware_concurrency();
std::vector<std::vector<std::weak_ptr<ImageData>>> splitDatas =
splitImageDatasToWeak( m_imageDatas, numThreads );
for( auto& dataRangeToLoad : splitDatas )
m_threads.push_back( std::make_unique<std::thread>(read, dataRangeToLoad) );
}
};
This implementation is nearly as easy as the first one, doesn't need any additional thread communication, and could be part of a thread pool/queue in a real implementation. Since the expired images are skipped, and non-expired images are processed, the threads never would have to be stopped during normal operation. You could always safely change the path or destroy your managers, since the reader fn checks, if the owning pointer isn't expired.
Just use JavaScript. Then compatible with most and older browsers. Use the escape sequence \n for newline.
document.getElementById("ElementID").title = 'First Line text \n Second line text'
textarea {
white-space: pre;
overflow-wrap: normal;
overflow-x: scroll;
}
white-space: nowrap
also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre
.
overflow-wrap: normal
(was word-wrap
in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre
is set.
also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap
seems to be the default on my browser.
swift 4
USE ALAMOFIRE in our App plz install pod file
pod 'Alamofire', '~> 4.0'
We can Use API for Json Data -https://swapi.co/api/people/
Then We can create A networking class for Our project- networkingService.swift
import Foundation
import Alamofire
typealias JSON = [String:Any]
class networkingService{
static let shared = networkingService()
private init() {}
func getPeople(success successblock: @escaping (GetPeopleResponse) -> Void)
{
Alamofire.request("https://swapi.co/api/people/").responseJSON { response in
guard let json = response.result.value as? JSON else {return}
// print(json)
do {
let getPeopleResponse = try GetPeopleResponse(json: json)
successblock(getPeopleResponse)
}catch{}
}
}
func getHomeWorld(homeWorldLink:String,completion: @escaping(String) ->Void){
Alamofire.request(homeWorldLink).responseJSON {(response) in
guard let json = response.result.value as? JSON,
let name = json["name"] as? String
else{return}
completion(name)
}
}
}
Then Create NetworkingError.swift class
import Foundation
enum networkingError : Error{
case badNetworkigStuff
}
Then create Person.swift class
import Foundation
struct Person {
private let homeWorldLink : String
let birthyear : String
let gender : String
let haircolor : String
let eyecolor : String
let height : String
let mass : String
let name : String
let skincolor : String
init?(json : JSON) {
guard let birthyear = json["birth_year"] as? String,
let eyecolor = json["eye_color"] as? String,
let gender = json["gender"] as? String,
let haircolor = json["hair_color"] as? String,
let height = json["height"] as? String,
let homeWorldLink = json["homeworld"] as? String,
let mass = json["mass"] as? String,
let name = json["name"] as? String,
let skincolor = json["skin_color"] as? String
else { return nil }
self.homeWorldLink = homeWorldLink
self.birthyear = birthyear
self.gender = gender
self.haircolor = haircolor
self.eyecolor = eyecolor
self.height = height
self.mass = mass
self.name = name
self.skincolor = skincolor
}
func homeWorld(_ completion: @escaping (String) -> Void) {
networkingService.shared.getHomeWorld(homeWorldLink: homeWorldLink){ (homeWorld) in
completion(homeWorld)
}
}
}
Then create DetailVC.swift
import UIKit
class DetailVC: UIViewController {
var person :Person!
@IBOutlet var name: UILabel!
@IBOutlet var birthyear: UILabel!
@IBOutlet var homeworld: UILabel!
@IBOutlet var eyeColor: UILabel!
@IBOutlet var skinColor: UILabel!
@IBOutlet var gender: UILabel!
@IBOutlet var hairColor: UILabel!
@IBOutlet var mass: UILabel!
@IBOutlet var height: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
print(person)
name.text = person.name
birthyear.text = person.birthyear
eyeColor.text = person.eyecolor
gender.text = person.gender
hairColor.text = person.haircolor
mass.text = person.mass
height.text = person.height
skinColor.text = person.skincolor
person.homeWorld{(homeWorld) in
self.homeworld.text = homeWorld
}
}
}
Then Create GetPeopleResponse.swift class
import Foundation
struct GetPeopleResponse {
let people : [Person]
init(json :JSON) throws {
guard let results = json["results"] as? [JSON] else { throw networkingError.badNetworkigStuff}
let people = results.map{Person(json: $0)}.flatMap{ $0 }
self.people = people
}
}
Then Our View controller class
import UIKit
class ViewController: UIViewController {
@IBOutlet var tableVieww: UITableView!
var people = [Person]()
@IBAction func getAction(_ sender: Any)
{
print("GET")
networkingService.shared.getPeople{ response in
self.people = response.people
self.tableVieww.reloadData()
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
guard segue.identifier == "peopleToDetails",
let detailVC = segue.destination as? DetailVC,
let person = sender as AnyObject as? Person
else {return}
detailVC.person = person
}
}
extension ViewController:UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return people.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = people[indexPath.row].name
return cell
}
}
extension ViewController:UITableViewDelegate{
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "peopleToDetails", sender: people[indexPath.row])
}
}
In our StoryBoard
plz Connect with our View with another one using segue with identifier -peopleToDetails
Use UITableView In our First View
Use UIButton For get the Data
Use 9 Labels in our DetailVc
You can do like this:
rename %CURR_DIR%\ftp\mywish1.txt text.txt
for /f %%a in (%CURR_DIR%\ftp\text.txt) do (
if "%%a" EQU "ex3" (
echo ex5 >> %CURR_DIR%\ftp\mywish1.txt
) else (
echo %%a >> %CURR_DIR%\ftp\mywish1.txt
)
)
del %CURR_DIR%\ftp\text.txt
take a look at shutil
. shutil.copyfile(src, dst)
will copy a file to another file.
Note that shutil.copyfile
will not create directories that do not already exist. for that, use os.makedirs
// logout
if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location:login.php');
}
?>
If you are using iscroll.js on webkit browser or mobile browser, you could try:
$('#pageWrapper>div:last-child').css('top', "0px");
I reckon the easiest way would be to use a built-in js functions decodeURI() / encodeURI().
function (usernameSent) {
var usernameEncoded = usernameSent; // Current value: utf8
var usernameDecoded = decodeURI(usernameReceived); // Decoded
// do stuff
}
You have to add a return statement if the condition
is false.
public String myMethod() {
if(condition) {
return x;
}
// if condition is false you HAVE TO return a string
// you could return a string, a empty string or null
return otherCondition;
}
FYI:
this one worked for me:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_your_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ... other stuff
}
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
The method onSupportNavigateUp() is called when you use the back button in the SupportActionBar.
I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)
just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc
Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
Indeed. The thing is that the 2008 R2 version is very tricky. The JTDs driver seems to work on some cases. In a certain server, the jTDS worked fine for an 2008 R2 instance. In another server, though, I had to use Microsoft's JBDC driver sqljdbc4.jar. But then, it would only work after setting the JRE environment to 1.6(or higher).
I used 1.5 for the other server, so I waisted a lot of time on this.
Tricky issue.
jQuery's hasClass()
method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.
For ex: x.hasClass('error');
First put this somewhere:
private <T> Iterable<T> iteratorToIterable(final Iterator<T> iterator) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return iterator;
}
};
}
Or if you have access to Java8, just this:
private <T> Iterable<T> iteratorToIterable(Iterator<T> iterator) {
return () -> iterator;
}
Then simply iterate over the object's keys and values:
for (String key : iteratorToIterable(object.keys())) {
JSONObject entry = object.getJSONObject(key);
// ...
While you are in debug mode within the catch {...}
block open up the "QuickWatch" window (ctrl+alt+q) and paste in there:
((System.Data.Entity.Validation.DbEntityValidationException)ex).EntityValidationErrors
or:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
If you are not in a try/catch or don't have access to the exception object.
This will allow you to drill down into the ValidationErrors
tree. It's the easiest way I've found to get instant insight into these errors.
$('#loginBtn').click(function(e) {
e.preventDefault(); /// it should not have this code or else it wont continue
//....
});
One can also use this kind of condition:
<div [ngStyle]="myBooleanVar && {'color': 'red'}"></div>
It requires a bit less string concatenation...
@eljenso : intrafest-servlet.xml webapplication context xml will be used if the application uses SPRING WEB MVC.
Otherwise the @kosoant configuration is fine.
Simple example if you dont use SPRING WEB MVC, but want to utitlize SPRING IOC :
In web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
Then, your application-context.xml will contain: <import resource="foo-services.xml"/>
these import statements to load various application context files and put into main application-context.xml.
Thanks and hope this helps.
This article sums it up pretty well
Summary: It's implementation dependent, as there is no specified limit in the RFC. It'd be safe to use up to 2000 characters (IE's limit.) If you are anywhere near this length, you should make sure you really need URIs that long, maybe an alternative design could get around that.
URIs should be readable, even when used to send data.
I think you are trying to over complicate things. A simple solution is to just style your checkbox by default with the unchecked styles and then add the checked state styles.
input[type="checkbox"] {
// Unchecked Styles
}
input[type="checkbox"]:checked {
// Checked Styles
}
I apologize for bringing up an old thread but felt like it could have used a better answer.
EDIT (3/3/2016):
W3C Specs state that :not(:checked)
as their example for selecting the unchecked state. However, this is explicitly the unchecked state and will only apply those styles to the unchecked state. This is useful for adding styling that is only needed on the unchecked state and would need removed from the checked state if used on the input[type="checkbox"]
selector. See example below for clarification.
input[type="checkbox"] {
/* Base Styles aka unchecked */
font-weight: 300; // Will be overwritten by :checked
font-size: 16px; // Base styling
}
input[type="checkbox"]:not(:checked) {
/* Explicit Unchecked Styles */
border: 1px solid #FF0000; // Only apply border to unchecked state
}
input[type="checkbox"]:checked {
/* Checked Styles */
font-weight: 900; // Use a bold font when checked
}
Without using :not(:checked)
in the example above the :checked
selector would have needed to use a border: none;
to achieve the same affect.
Use the input[type="checkbox"]
for base styling to reduce duplication.
Use the input[type="checkbox"]:not(:checked)
for explicit unchecked styles that you do not want to apply to the checked state.
@datenstation had the correct concept. Here is a working example that uses CTE to cache variable's names:
CREATE VIEW vwImportant_Users AS
WITH params AS (
SELECT
varType='%Admin%',
varMinStatus=1)
SELECT status, name
FROM sys.sysusers, params
WHERE status > varMinStatus OR name LIKE varType
SELECT * FROM vwImportant_Users
also via JOIN
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers INNER JOIN params ON 1=1
WHERE status > varMinStatus OR name LIKE varType
also via CROSS APPLY
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers CROSS APPLY params
WHERE status > varMinStatus OR name LIKE varType
Removing a file from pull request but not from your local repository.
git checkout -- c:\temp..... next git checkout origin/master -- c:\temp... u replace origin/master with any other branch. Next git commit -m c:\temp..... Next git push origin
Note : no single quote or double quotes for the filepath
You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME
You could create a unique index with a coalesce on the MenuId:
CREATE UNIQUE INDEX
Favorites_UniqueFavorite ON Favorites
(UserId, COALESCE(MenuId, '00000000-0000-0000-0000-000000000000'), RecipeId);
You'd just need to pick a UUID for the COALESCE that will never occur in "real life". You'd probably never see a zero UUID in real life but you could add a CHECK constraint if you are paranoid (and since they really are out to get you...):
alter table Favorites
add constraint check
(MenuId <> '00000000-0000-0000-0000-000000000000')
if you know the length of your rows you can make something like this:
a=rand(9,3);
b=rand(9,3);
arrayfun(@(x1,x2,y1,y2,z1,z2) line([x1,x2],[y1,y2],[z1,z2]) , a(:,1),b(:,1),a(:,2),b(:,2),a(:,3),b(:,3) )
I had a similar issue not long time ago and this was how I solved it
.rotated-half-circle {_x000D_
/* Create the circle */_x000D_
width: 40px;_x000D_
height: 40px;_x000D_
border: 10px solid black;_x000D_
border-radius: 50%;_x000D_
/* Halve the circle */_x000D_
border-bottom-color: transparent;_x000D_
border-left-color: transparent;_x000D_
/* Rotate the circle */_x000D_
transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="rotated-half-circle"></div>
_x000D_
Get the full Android-SDK plus the dependencies at http://developer.android.com/sdk/index.html.
Do have Java installed :)
I tried changing year
to a different term, and it worked.
public_methods : {
get: function() {
return this._year;
},
set: function(newValue) {
if(newValue > this.originYear) {
this._year = newValue;
this.edition += newValue - this.originYear;
}
}
}
If the directory doesn't exist you need to create it. Java won't create it by itself since the File
class is just a link to an entity that can also not exist at all.
As you stated the error is that the file cannot be created. If you read the documentation of PrintWriter constructor you can see
FileNotFoundException - If the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, or if some other error occurs while opening or creating the file
You should try creating a path for the folder it contains before:
File file = new File("C:/Users/Me/Desktop/directory/file.txt");
file.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(file);
We can use setTag()
and getTag()
to set and get custom objects as per our requirement. The setTag()
method takes an argument of type Object
, and getTag()
returns an Object
.
For example,
Person p = new Person();
p.setName("Ramkailash");
p.setId(2000001);
button1.setTag(p);
Instead of
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
Use
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
We can use tr command to split string into the array object. It works both MacOS and Linux
#!/usr/bin/env bash
currentVersion="1.0.0.140"
arrayData=($(echo $currentVersion | tr "." "\n"))
len=${#arrayData[@]}
for (( i=0; i<=$((len-1)); i++ )); do
echo "index $i - value ${arrayData[$i]}"
done
Another option use IFS command
IFS='.' read -ra arrayData <<< "$currentVersion"
#It is the same as tr
arrayData=($(echo $currentVersion | tr "." "\n"))
#Print the split string
for i in "${arrayData[@]}"
do
echo $i
done
See execSync library.
It's fairly easy to do with node-ffi. I wouldn't recommend for server processes, but for general development utilities it gets things done. Install the library.
npm install node-ffi
Example script:
var FFI = require("node-ffi");
var libc = new FFI.Library(null, {
"system": ["int32", ["string"]]
});
var run = libc.system;
run("echo $USER");
[EDIT Jun 2012: How to get STDOUT]
var lib = ffi.Library(null, {
// FILE* popen(char* cmd, char* mode);
popen: ['pointer', ['string', 'string']],
// void pclose(FILE* fp);
pclose: ['void', [ 'pointer']],
// char* fgets(char* buff, int buff, in)
fgets: ['string', ['string', 'int','pointer']]
});
function execSync(cmd) {
var
buffer = new Buffer(1024),
result = "",
fp = lib.popen(cmd, 'r');
if (!fp) throw new Error('execSync error: '+cmd);
while(lib.fgets(buffer, 1024, fp)) {
result += buffer.readCString();
};
lib.pclose(fp);
return result;
}
console.log(execSync('echo $HOME'));
Here's a jQuery-ised function of Innuendo's answer, ready for use.
$.extend({
keyCount : function(o) {
if(typeof o == "object") {
var i, count = 0;
for(i in o) {
if(o.hasOwnProperty(i)) {
count++;
}
}
return count;
} else {
return false;
}
}
});
Can be called like this:
var cnt = $.keyCount({"foo" : "bar"}); //cnt = 1;
This will prefix your files in their directory.
The ${f%/*}
is the path till the last slash /
-> the directory
The ${f##*/}
is the text without anything before last slash /
-> filename without the path
So that's how it goes:
for f in $(find /directory/ -type f); do
mv -v $f ${f%/*}/$(date +%Y%m%d)_Prefix_${f##*/}
done
Your getElementById
is looking for an element with id "myclass", but in your html the id of the DIV is showhide
. Change to:
<script>
function changeclass() {
var NAME = document.getElementById("showhide")
NAME.className="mynewclass"
}
</script>
Unless you are trying to target a different element with the id "myclass", then you need to make sure such an element exists.
To extend answers above, you cannot use Guid default value with Guid.Empty
as an optional argument in method, indexer or delegate definition, because it will give you compile time error. Use default(Guid)
or new Guid()
instead.
Use the DATE function:
SELECT DATE(orders.date_purchased) AS date
All containers offer a reversed view of their content with rbegin()
and rend()
. These two functions return so-calles reverse iterators, which can be used like normal ones, but it will look like the container is actually reversed.
#include <vector>
#include <iostream>
template<class InIt>
void print_range(InIt first, InIt last, char const* delim = "\n"){
--last;
for(; first != last; ++first){
std::cout << *first << delim;
}
std::cout << *first;
}
int main(){
int a[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(a, a+5);
print_range(v.begin(), v.end(), "->");
std::cout << "\n=============\n";
print_range(v.rbegin(), v.rend(), "<-");
}
Live example on Ideone. Output:
1->2->3->4->5
=============
5<-4<-3<-2<-1
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
I use doctest[1] almost everywhere because I like the fact that I document and test my functions at the same time.
Have a look at this code:
def throw_up(something, gowrong=False):
"""
>>> throw_up('Fish n Chips')
Traceback (most recent call last):
...
Exception: Fish n Chips
>>> throw_up('Fish n Chips', gowrong=True)
'I feel fine!'
"""
if gowrong:
return "I feel fine!"
raise Exception(something)
if __name__ == '__main__':
import doctest
doctest.testmod()
If you put this example in a module and run it from the command line both test cases are evaluated and checked.
[1] Python documentation: 23.2 doctest -- Test interactive Python examples
For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n)
, where n
is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort
. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.
So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....
You can pass multiple arguments like this.
List<object> arguments = new List<object>();
arguments.Add("first"); //argument 1
arguments.Add(new Object()); //argument 2
// ...
arguments.Add(10); //argument n
backgroundWorker.RunWorkerAsync(arguments);
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
List<object> genericlist = e.Argument as List<object>;
//extract your multiple arguments from
//this list and cast them and use them.
}
Simple? Yup.
If you multiply two large prime numbers, you get a huge non-prime number with only two (large) prime factors.
Factoring that number is a non-trivial operation, and that fact is the source of a lot of Cryptographic algorithms. See one-way functions for more information.
Addendum: Just a bit more explanation. The product of the two prime numbers can be used as a public key, while the primes themselves as a private key. Any operation done to data that can only be undone by knowing one of the two factors will be non-trivial to unencrypt.
Not to be blunt but it means exactly what it says. One of your object references is NULL. You'll see this when you try and access the property or method of a NULL'd object.
I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:
$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
$date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
$availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
$date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
Start-Sleep -s 2
}
This produces the following output:
2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)
You can hit Ctrl+C
to abort the loop.
So, you can connect to any Windows machine with this command:
Enter-PSSession -ComputerName MyServerName -Credential MyUserName
...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.
Thought I'd add an answer since your question title looks like it is asking how to create or update, rather than get or create as described in the question body.
If you did want to create or update an object, the .save() method already has this behaviour by default, from the docs:
Django abstracts the need to use INSERT or UPDATE SQL statements. Specifically, when you call save(), Django follows this algorithm:
If the object’s primary key attribute is set to a value that evaluates to True (i.e., a value other than None or the empty string), Django executes an UPDATE. If the object’s primary key attribute is not set or if the UPDATE didn’t update anything, Django executes an INSERT.
It's worth noting that when they say 'if the UPDATE didn't update anything' they are essentially referring to the case where the id you gave the object doesn't already exist in the database.
Keeping it simple, if you want the request to use the same browsing context as the page you are already looking at then in the Chrome console just do:
window.location="https://www.example.com";
extension StringProtocol where Index == String.Index {
func nsRange(of string: String) -> NSRange? {
guard let range = self.range(of: string) else { return nil }
return NSRange(range, in: self)
}
}
As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());
mainFrame.pack();
mainFrame.setVisible(true);
GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.
This works for me:
var tP = $("img").css("padding").split(" ");
var Padding = {
Top: tP[0] != null ? parseInt(tP[0]) : 0,
Right: tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0),
Bottom: tP[2] != null ? parseInt(tP[2]) : (tP[0] != null ? parseInt(tP[0]) : 0),
Left: tP[3] != null ? parseInt(tP[3]) : (tP[1] != null ? parseInt(tP[1]) : (tP[0] != null ? parseInt(tP[0]) : 0))
};
Result example:
Object {Top: 5, Right: 8, Bottom: 5, Left: 8}
To make a total:
var TotalPadding = Padding.Top + Padding.Right + Padding.Bottom + Padding.Left;
if you want generate a random float with N digits to the right of point, you can make this :
round(random.uniform(1,2), N)
the second argument is the number of decimals.
I think that using the event tabPage1.Enter
is more convenient.
tabPage1.Enter += new System.EventHandler(tabPage1_Enter);
private void tabPage1_Enter(object sender, EventArgs e)
{
MessageBox.Show("you entered tabPage1");
}
This is better than having nested if-else statement when you have different logic for different tabs. And more suitable in case new tabs may be added in the future.
Note that this event fires if the form loads and tabPage1
is opened by default.
I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.
Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
This jQuery plugin gives you a pre-made way of selection/caret manipulation.
In addition to the syntactic and operational properties, there's also a semantical difference.
Delegates are, conceptually, function templates; that is, they express a contract a function must adhere to in order to be considered of the "type" of the delegate.
Events represent ... well, events. They are intended to alert someone when something happens and yes, they adhere to a delegate definition but they're not the same thing.
Even if they were exactly the same thing (syntactically and in the IL code) there will still remain the semantical difference. In general I prefer to have two different names for two different concepts, even if they are implemented in the same way (which doesn't mean I like to have the same code twice).
I found the best way to troubleshoot this issue is to create a .proj msbuild file and add your unit test projects which you hare having an issue into this file and execute the tests using the command line version of mstest. I found a small configuration issue in my app.config which only appeared when running the tests from mstest - otherwise the test project built just fine. Also you will find any indirect reference issues with this method as well. Once you can run the Unit test from the command line using mstest you can then do a clean solution, rebuild solution and your test should be discovered properly.
Groovy has operator overloading, and runs in the JVM. If you don't mind the performance hit (which gets smaller everyday). It's automatic based on method names. e.g., '+' calls the 'plus(argument)' method.
As SLF4J Manual states
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks, such as java.util.logging, logback and log4j.
and
The warning will disappear as soon as you add a binding to your class path.
So you should choose which binding do you want to use.
NoOp binding (slf4j-nop)
Binding for NOP, silently discarding all logging.
Check fresh version at https://search.maven.org/search?q=g:org.slf4j%20AND%20a:slf4j-nop&core=gav
Simple binding (slf4j-simple)
outputs all events to System.err. Only messages of level INFO and higher are printed. This binding may be useful in the context of small applications.
Check fresh version at https://search.maven.org/search?q=g:org.slf4j%20AND%20a:slf4j-simple&core=gav
Bindings for the logging frameworks (java.util.logging, logback, log4j)
You need one of these bindings if you are going to write log to a file.
See description and instructions at https://www.slf4j.org/manual.html#projectDep
My opinion
I would recommend Logback because it's a successor to the log4j project.
Check latest version of the binding for it at https://search.maven.org/search?q=g:ch.qos.logback%20AND%20a:logback-classic&core=gav
You get console output out of the box but if you need to write logs into file just put FileAppender
configuration to the src/main/resources/logback.xml
or to the src/test/resources/logback-test.xml
just like this:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>logs/logs.log</file>
<encoder>
<pattern>%date %level [%thread] %logger{10} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />
</root>
<logger level="DEBUG" name="com.myapp"/>
</configuration>
(See detailed description in manual: https://logback.qos.ch/manual/configuration.html)
to set text in kotlin
textview.text = "write here"
Simple and clean solution using Interface Builder
Add a file named UIView.swift in your project (or just paste this in any file) :
import UIKit
@IBDesignable extension UIView {
/* The color of the shadow. Defaults to opaque black. Colors created
* from patterns are currently NOT supported. Animatable. */
@IBInspectable var shadowColor: UIColor? {
set {
layer.shadowColor = newValue!.CGColor
}
get {
if let color = layer.shadowColor {
return UIColor(CGColor:color)
}
else {
return nil
}
}
}
/* The opacity of the shadow. Defaults to 0. Specifying a value outside the
* [0,1] range will give undefined results. Animatable. */
@IBInspectable var shadowOpacity: Float {
set {
layer.shadowOpacity = newValue
}
get {
return layer.shadowOpacity
}
}
/* The shadow offset. Defaults to (0, -3). Animatable. */
@IBInspectable var shadowOffset: CGPoint {
set {
layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y)
}
get {
return CGPoint(x: layer.shadowOffset.width, y:layer.shadowOffset.height)
}
}
/* The blur radius used to create the shadow. Defaults to 3. Animatable. */
@IBInspectable var shadowRadius: CGFloat {
set {
layer.shadowRadius = newValue
}
get {
return layer.shadowRadius
}
}
}
Then this will be available in Interface Builder for every view in the Utilities Panel > Attributes Inspector :
You can easily set the shadow now.
Notes:
- The shadow won't appear in IB, only at runtime.
- As Mazen Kasser said
To those who failed in getting this to work [...] make sure Clip Subviews (
clipsToBounds
) is not enabled
UIActionSheet
is deprecated in iOS 8.
I am using following:
// Create the AlertController
let actionSheetController = UIAlertController(title: "Please select", message: "How you would like to utilize the app?", preferredStyle: .ActionSheet)
// Create and add the Cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
// Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
// Create and add first option action
let takePictureAction = UIAlertAction(title: "Consumer", style: .Default) { action -> Void in
self.performSegueWithIdentifier("segue_setup_customer", sender: self)
}
actionSheetController.addAction(takePictureAction)
// Create and add a second option action
let choosePictureAction = UIAlertAction(title: "Service provider", style: .Default) { action -> Void in
self.performSegueWithIdentifier("segue_setup_provider", sender: self)
}
actionSheetController.addAction(choosePictureAction)
// We need to provide a popover sourceView when using it on iPad
actionSheetController.popoverPresentationController?.sourceView = sender as UIView
// Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
I had the same problem - solved it by setting display_errors = On
in both php.ini
files.
/etc/php5/apache2/php.ini
/etc/php5/cli/php.ini
Then restarting Apache:
sudo /etc/init.d/apache2 restart
Hope this helps.
Another way is to write
@user.route('/<user_id>', defaults={'username': None})
@user.route('/<user_id>/<username>')
def show(user_id, username):
pass
But I guess that you want to write a single route and mark username
as optional? If that's the case, I don't think it's possible.
The cursor is the Interface that represents a 2-dimensional
table of any database.
When you try to retrieve some data using SELECT
statement, then the database will 1st create a CURSOR object and return its reference to you.
The pointer of this returned reference is pointing to the 0th location which is otherwise called as before the first location of the Cursor, so when you want to retrieve data from the cursor, you have to 1st move to the 1st record so we have to use moveToFirst
When you invoke moveToFirst()
method on the Cursor, it takes the cursor pointer to the 1st location. Now you can access the data present in the 1st record
The best way to look :
Cursor cursor
for (cursor.moveToFirst();
!cursor.isAfterLast();
cursor.moveToNext()) {
.........
}
what worked for me is just define the variable outside this function of your.
Just before main function declare i.e.
Double price;
public static void main(String []args(){
--------
--------
}
Just to have an answer with the complete solution to help the visitors:
All you need to do is add the junit dependency to pom.xml
. Don't forget the <scope>test</scope>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
Try the following query:
;WITH CTE_DocTotal
AS
(
SELECT SUM(Sale + VAT) AS DocTotal_1
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
)
UPDATE CTE_DocTotal
SET DocTotal = CTE_DocTotal.DocTotal_1
So, having glanced quickly through some of these and other similar questions I went on a merry goose chase this afternoon trying to solve a problem with two separate programs using a file as a synchronization (and also file save) method. A bit of an unusual situation, but it definitely highlighted for me the problems with the 'check if the file is locked, then open it if it's not' approach.
The problem is this: the file can become locked between the time that you check it and the time you actually open the file. Its really hard to track down the sporadic Cannot copy the file, because it's used by another process error if you aren't looking for it too.
The basic resolution is to just try to open the file inside a catch block so that if its locked, you can try again. That way there is no elapsed time between the check and the opening, the OS does them at the same time.
The code here uses File.Copy, but it works just as well with any of the static methods of the File class: File.Open, File.ReadAllText, File.WriteAllText, etc.
/// <param name="timeout">how long to keep trying in milliseconds</param>
static void safeCopy(string src, string dst, int timeout)
{
while (timeout > 0)
{
try
{
File.Copy(src, dst);
//don't forget to either return from the function or break out fo the while loop
break;
}
catch (IOException)
{
//you could do the sleep in here, but its probably a good idea to exit the error handler as soon as possible
}
Thread.Sleep(100);
//if its a very long wait this will acumulate very small errors.
//For most things it's probably fine, but if you need precision over a long time span, consider
// using some sort of timer or DateTime.Now as a better alternative
timeout -= 100;
}
}
Another small note on parellelism: This is a synchronous method, which will block its thread both while waiting and while working on the thread. This is the simplest approach, but if the file remains locked for a long time your program may become unresponsive. Parellelism is too big a topic to go into in depth here, (and the number of ways you could set up asynchronous read/write is kind of preposterous) but here is one way it could be parellelized.
public class FileEx
{
public static async void CopyWaitAsync(string src, string dst, int timeout, Action doWhenDone)
{
while (timeout > 0)
{
try
{
File.Copy(src, dst);
doWhenDone();
break;
}
catch (IOException) { }
await Task.Delay(100);
timeout -= 100;
}
}
public static async Task<string> ReadAllTextWaitAsync(string filePath, int timeout)
{
while (timeout > 0)
{
try {
return File.ReadAllText(filePath);
}
catch (IOException) { }
await Task.Delay(100);
timeout -= 100;
}
return "";
}
public static async void WriteAllTextWaitAsync(string filePath, string contents, int timeout)
{
while (timeout > 0)
{
try
{
File.WriteAllText(filePath, contents);
return;
}
catch (IOException) { }
await Task.Delay(100);
timeout -= 100;
}
}
}
And here is how it could be used:
public static void Main()
{
test_FileEx();
Console.WriteLine("Me First!");
}
public static async void test_FileEx()
{
await Task.Delay(1);
//you can do this, but it gives a compiler warning because it can potentially return immediately without finishing the copy
//As a side note, if the file is not locked this will not return until the copy operation completes. Async functions run synchronously
//until the first 'await'. See the documentation for async: https://msdn.microsoft.com/en-us/library/hh156513.aspx
CopyWaitAsync("file1.txt", "file1.bat", 1000);
//this is the normal way of using this kind of async function. Execution of the following lines will always occur AFTER the copy finishes
await CopyWaitAsync("file1.txt", "file1.readme", 1000);
Console.WriteLine("file1.txt copied to file1.readme");
//The following line doesn't cause a compiler error, but it doesn't make any sense either.
ReadAllTextWaitAsync("file1.readme", 1000);
//To get the return value of the function, you have to use this function with the await keyword
string text = await ReadAllTextWaitAsync("file1.readme", 1000);
Console.WriteLine("file1.readme says: " + text);
}
//Output:
//Me First!
//file1.txt copied to file1.readme
//file1.readme says: Text to be duplicated!
A little bit about performance
UI Testing Bundle
on iPhone 7(real device) with iOS 14
let i = 0
lt result1 = String(i) //0.56s 5890kB
lt result2 = "\(i)" //0.624s 5900kB
lt result3 = i.description //0.758s 5890kB
import XCTest
class ConvertIntToStringTests: XCTestCase {
let count = 1_000_000
func measureFunction(_ block: () -> Void) {
let metrics: [XCTMetric] = [
XCTClockMetric(),
XCTMemoryMetric()
]
let measureOptions = XCTMeasureOptions.default
measureOptions.iterationCount = 5
measure(metrics: metrics, options: measureOptions) {
block()
}
}
func testIntToStringConstructor() {
var result = ""
measureFunction {
for i in 0...count {
result += String(i)
}
}
}
func testIntToStringInterpolation() {
var result = ""
measureFunction {
for i in 0...count {
result += "\(i)"
}
}
}
func testIntToStringDescription() {
var result = ""
measureFunction {
for i in 0...count {
result += i.description
}
}
}
}
For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'});
only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)
It could just be something that runs once the first time you initialize collapse with those parameters.
You will have more luck using the show
and hide
methods.
Here is an example:
$(function() {
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('.collapse-init').on('click', function() {
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
$('.panel-collapse').collapse('show');
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
});
});
Update
Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.
I don't understand what's going on or why the show
seemed to be toggling in some places.
But After messing around for a while.. Finally came with the following solution:
$(function() {
var transition = false;
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('#accordion').on('show.bs.collapse',function(){
if($active){
$('#accordion .in').collapse('hide');
}
});
$('#accordion').on('hidden.bs.collapse',function(){
if(transition){
transition = false;
$('.panel-collapse').collapse('show');
}
});
$('.collapse-init').on('click', function() {
$('.collapse-init').prop('disabled','true');
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
if($('.panel-collapse.in').length){
transition = true;
$('.panel-collapse.in').collapse('hide');
}
else{
$('.panel-collapse').collapse('show');
}
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
setTimeout(function(){
$('.collapse-init').prop('disabled','');
},800);
});
});
Let's first look at the definitions of these words before evaluating what the difference is in HTML:
English definition:
In HTML context:
When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:
It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.
Furthermore have different DOM elements different properties. For example, an <input>
element has a value property which is not present on a <div>
property.
Let's take the following HTML document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <!-- charset is a attribute -->
<meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
<title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>
Then we inspect the <div>
, in the JS console:
console.dir(document.getElementById('foo'));
We see the following DOM properties (chrome devtools, not all properties shown):
class
is reserved keyword in JS). But actually 2 properties, classList
and className
.Along the same lines, I use the following in my .vimrc
to let me move through the splits, automatically expanding the one I'm moving to to its full size and shrinking all the rest to their minimum height or width:
" Switch between window splits using big J or K and expand the split to its
" full size.
"
" Move vertically in the window through the horizontal splits...
map <C-J> <C-w>j<C-w>_
map <C-K> <C-w>k<C-w>_
" Move horizontally in the window through the vertical splits...
map <C-H> <C-w>h<C-w>\|
map <C-L> <C-w>l<C-w>\|
Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.
- name: Set fact 4
set_fact:
foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"
I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.
- name: build foo_string
set_fact:
foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"
- name: set fact foo
set_fact:
foo: "{{ foo_string.split(',') }}"
Yes, this is a current issue in Chrome. There is an issue report here.
The fix will appear in 40.x.y.z versions.
Until then? I don't think you can resolve the issue yourself. But you can ignore it. The shown error is only related to the dev tools and does not influence the behavior of your website. If you have any other problems they are not related to this error.
As others have pointed out, there are many web frameworks for Python.
But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:
Rename your script to index.cgi
. You also need to execute chmod +x index.cgi
to give it execution privileges.
Add these 2 lines in the beginning of the file:
#!/usr/bin/python print('Content-type: text/html\r\n\r')
After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.
Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python
might work instead.
You're referencing a DOM element when doing something like $('#lastName')
. That's an element with id
attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject
is in the same scope as the variable declarations) -
var formObject = {
formObject: [
{
firstName:firstName, // no need to quote variable names
lastName:lastName
},
{
phoneNumber:phoneNumber,
address:address
}
]
};
This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
They must have included this as a feature, because now setting a different @JsonProperty
for a getter and setter results in exactly what you would expect (different property name during serialization and deserialization for the same field). Jackson version 2.6.7
According to Flexbugs:
In IE 10-11,
min-height
declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.
Here are a couple of workarounds:
<aside>
and <section>
:html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1;
display: flex;
}
aside, section {
overflow: auto;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
html {
height: 100%;
}
body {
display: flex;
flex-direction: column;
height: 100%;
margin: 0;
}
header,
footer {
background: #7092bf;
}
main {
flex: 1 0 auto;
display: flex;
}
aside {
flex: 0 0 150px;
background: #3e48cc;
}
section {
flex: 1;
background: #9ad9ea;
}
_x000D_
<header>
<p>header</p>
</header>
<main>
<aside>
<p>aside</p>
</aside>
<section>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
<p>content</p>
</section>
</main>
<footer>
<p>footer</p>
</footer>
_x000D_
A simple way using std::next_permutation
:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.end() - r, v.end(), true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::next_permutation(v.begin(), v.end()));
return 0;
}
or a slight variation that outputs the results in an easier to follow order:
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
int n, r;
std::cin >> n;
std::cin >> r;
std::vector<bool> v(n);
std::fill(v.begin(), v.begin() + r, true);
do {
for (int i = 0; i < n; ++i) {
if (v[i]) {
std::cout << (i + 1) << " ";
}
}
std::cout << "\n";
} while (std::prev_permutation(v.begin(), v.end()));
return 0;
}
A bit of explanation:
It works by creating a "selection array" (v
), where we place r
selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v
.
You can implement it if you note that for each level r you select a number from 1 to n.
In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance
#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>
using namespace std;
struct combinations
{
typedef vector<int> combination_t;
// initialize status
combinations(int N, int R) :
completed(N < 1 || R > N),
generated(0),
N(N), R(R)
{
for (int c = 1; c <= R; ++c)
curr.push_back(c);
}
// true while there are more solutions
bool completed;
// count how many generated
int generated;
// get current and compute next combination
combination_t next()
{
combination_t ret = curr;
// find what to increment
completed = true;
for (int i = R - 1; i >= 0; --i)
if (curr[i] < N - R + i + 1)
{
int j = curr[i] + 1;
while (i <= R-1)
curr[i++] = j++;
completed = false;
++generated;
break;
}
return ret;
}
private:
int N, R;
combination_t curr;
};
int main(int argc, char **argv)
{
int N = argc >= 2 ? atoi(argv[1]) : 5;
int R = argc >= 3 ? atoi(argv[2]) : 2;
combinations cs(N, R);
while (!cs.completed)
{
combinations::combination_t c = cs.next();
copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
cout << endl;
}
return cs.generated;
}
test output:
1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,
You must use plt.show()
at the end in order to see the plot
For the substition impaired here is a real example from GitHub.com to a local directory:
svn ls https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces
svn export https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces /temp/SvnExport/Washburn
See: Download a single folder or directory from a GitHub repo for more details.
BY ABDULHAYEE:
NoClassDefFoundError in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time. For example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw NoClassDefFoundError. It’s important to understand that this is different than ClassNotFoundException which comes while trying to load a class at run-time only and name was provided during runtime not on compile time. Many Java developer mingle this two Error and gets confused.
In short NoClassDefFoundError will come if a class was present during compile time but not available in java classpath during runtime. Normally you will see below line in log when you get NoClassDefFoundError: Exception in thread "main" java.lang.NoClassDefFoundError Exception in thread “main” simply indicate that its “main” thread which is not able to find a particular class it could be any thread so just don’t worry . Difference between this error coming in main thread and other thread is , whenException in thread “main” comes program crashes or shut it self down as opposed to other thread in which case your program will continue to run.,
Read more: http://javarevisited.blogspot.com/2011/06/noclassdeffounderror-exception-in.html#ixzz2jr35SsaZ
You don't add or link directly against a DLL, you link against the LIB produced by the DLL.
A LIB provides symbols and other necessary data to either include a library in your code (static linking) or refer to the DLL (dynamic linking).
To link against a LIB, you need to add it to the project Properties -> Linker -> Input -> Additional Dependencies list. All LIB files here will be used in linking. You can also use a pragma like so:
#pragma comment(lib, "dll.lib")
With static linking, the code is included in your executable and there are no runtime dependencies. Dynamic linking requires a DLL with matching name and symbols be available within the search path (which is not just the path or system directory).
Here's a one page cart written in Javascript with localStorage. Here's a full working pen. Previously found on Codebox
cart.js
var cart = {
// (A) PROPERTIES
hPdt : null, // HTML products list
hItems : null, // HTML current cart
items : {}, // Current items in cart
// (B) LOCALSTORAGE CART
// (B1) SAVE CURRENT CART INTO LOCALSTORAGE
save : function () {
localStorage.setItem("cart", JSON.stringify(cart.items));
},
// (B2) LOAD CART FROM LOCALSTORAGE
load : function () {
cart.items = localStorage.getItem("cart");
if (cart.items == null) { cart.items = {}; }
else { cart.items = JSON.parse(cart.items); }
},
// (B3) EMPTY ENTIRE CART
nuke : function () {
if (confirm("Empty cart?")) {
cart.items = {};
localStorage.removeItem("cart");
cart.list();
}
},
// (C) INITIALIZE
init : function () {
// (C1) GET HTML ELEMENTS
cart.hPdt = document.getElementById("cart-products");
cart.hItems = document.getElementById("cart-items");
// (C2) DRAW PRODUCTS LIST
cart.hPdt.innerHTML = "";
let p, item, part;
for (let id in products) {
// WRAPPER
p = products[id];
item = document.createElement("div");
item.className = "p-item";
cart.hPdt.appendChild(item);
// PRODUCT IMAGE
part = document.createElement("img");
part.src = "images/" +p.img;
part.className = "p-img";
item.appendChild(part);
// PRODUCT NAME
part = document.createElement("div");
part.innerHTML = p.name;
part.className = "p-name";
item.appendChild(part);
// PRODUCT DESCRIPTION
part = document.createElement("div");
part.innerHTML = p.desc;
part.className = "p-desc";
item.appendChild(part);
// PRODUCT PRICE
part = document.createElement("div");
part.innerHTML = "$" + p.price;
part.className = "p-price";
item.appendChild(part);
// ADD TO CART
part = document.createElement("input");
part.type = "button";
part.value = "Add to Cart";
part.className = "cart p-add";
part.onclick = cart.add;
part.dataset.id = id;
item.appendChild(part);
}
// (C3) LOAD CART FROM PREVIOUS SESSION
cart.load();
// (C4) LIST CURRENT CART ITEMS
cart.list();
},
// (D) LIST CURRENT CART ITEMS (IN HTML)
list : function () {
// (D1) RESET
cart.hItems.innerHTML = "";
let item, part, pdt;
let empty = true;
for (let key in cart.items) {
if(cart.items.hasOwnProperty(key)) { empty = false; break; }
}
// (D2) CART IS EMPTY
if (empty) {
item = document.createElement("div");
item.innerHTML = "Cart is empty";
cart.hItems.appendChild(item);
}
// (D3) CART IS NOT EMPTY - LIST ITEMS
else {
let p, total = 0, subtotal = 0;
for (let id in cart.items) {
// ITEM
p = products[id];
item = document.createElement("div");
item.className = "c-item";
cart.hItems.appendChild(item);
// NAME
part = document.createElement("div");
part.innerHTML = p.name;
part.className = "c-name";
item.appendChild(part);
// REMOVE
part = document.createElement("input");
part.type = "button";
part.value = "X";
part.dataset.id = id;
part.className = "c-del cart";
part.addEventListener("click", cart.remove);
item.appendChild(part);
// QUANTITY
part = document.createElement("input");
part.type = "number";
part.value = cart.items[id];
part.dataset.id = id;
part.className = "c-qty";
part.addEventListener("change", cart.change);
item.appendChild(part);
// SUBTOTAL
subtotal = cart.items[id] * p.price;
total += subtotal;
}
// EMPTY BUTTONS
item = document.createElement("input");
item.type = "button";
item.value = "Empty";
item.addEventListener("click", cart.nuke);
item.className = "c-empty cart";
cart.hItems.appendChild(item);
// CHECKOUT BUTTONS
item = document.createElement("input");
item.type = "button";
item.value = "Checkout - " + "$" + total;
item.addEventListener("click", cart.checkout);
item.className = "c-checkout cart";
cart.hItems.appendChild(item);
}
},
// (E) ADD ITEM INTO CART
add : function () {
if (cart.items[this.dataset.id] == undefined) {
cart.items[this.dataset.id] = 1;
} else {
cart.items[this.dataset.id]++;
}
cart.save();
cart.list();
},
// (F) CHANGE QUANTITY
change : function () {
if (this.value == 0) {
delete cart.items[this.dataset.id];
} else {
cart.items[this.dataset.id] = this.value;
}
cart.save();
cart.list();
},
// (G) REMOVE ITEM FROM CART
remove : function () {
delete cart.items[this.dataset.id];
cart.save();
cart.list();
},
// (H) CHECKOUT
checkout : function () {
// SEND DATA TO SERVER
// CHECKS
// SEND AN EMAIL
// RECORD TO DATABASE
// PAYMENT
// WHATEVER IS REQUIRED
alert("TO DO");
/*
var data = new FormData();
data.append('cart', JSON.stringify(cart.items));
data.append('products', JSON.stringify(products));
var xhr = new XMLHttpRequest();
xhr.open("POST", "SERVER-SCRIPT");
xhr.onload = function(){ ... };
xhr.send(data);
*/
}
};
window.addEventListener("DOMContentLoaded", cart.init);
To create a label for text:
JLabel label1 = new JLabel("Test");
To change the text in the label:
label1.setText("Label Text");
And finally to clear the label:
label1.setText("");
And all you have to do is place the label in your layout, or whatever layout system you are using, and then just add it to the JFrame...
I don't think it's enough merely to get the response. I think you need to read it (get the entity and read it via EntityUtils.consume()).
e.g. (from the doc)
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
If you're using GitHub and haven't yet pushed the commit, GitHub Desktop solves this problem easily:
the implementation in the cpp file should be in the form
gameObject::gameObject()
{
x = 0;
y = 0;
}
gameObject::gameObject(int inx, int iny)
{
x = inx;
y = iny;
}
gameObject::~gameObject()
{
//
}
int gameObject::add()
{
return x+y;
}
not within a class gameObject { } definition block
I have used paramiko a bunch (nice) and pxssh (also nice). I would recommend either. They work a little differently but have a relatively large overlap in usage.
Use set()
:
woduplicates = set(lseparatedOrblist)
Returns a set without duplicates. If you, for some reason, need a list back:
woduplicates = list(set(lseperatedOrblist))
This will, however, have a different order than your original list.
I also had to add white-space: nowrap;
to the style, otherwise elements would wrap down into the area that we're removing the ability to scroll to.
Your firewall does not allow any new connection to share information without your consent. ONLY thing to do is give your consent to your firewall.
Go to Firewall settings in Control Panel
Click on Advanced Settings
Click on Inbound Rules and Add a new rule.
Choose 'Type Of Rule' to Port.
Allow this for All Programs.
Allow this rule to be applied on all Profiles i.e. Domain, Private, Public.
Give this rule any name.
That's it. Now another PC and mobiles connected on the same network can access the local sites. Lets Start Development.
Tough one for a newbie like me - here is a screenshot that describes it.
Xcode 10.2.1
$move = "/Users/George/Desktop/uploads/".$_FILES['file']['name'];
That's one.
move_uploaded_file($_FILES['file']['tmp_name'], $move);
That's two.
Check if the uploads
dir is writeable
That's three.
Return Values
Returns TRUE on success.
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.
Look at return value of the function.
That's it.
ls /bin/python*
Identify the highest version of python listed.
If the highest version is something like python2.7
then install python2-pip
If its something like python3.8
then install python3-pip
Example for python3.8:
sudo apt-get install python3-pip
Alternate syntax,
git fetch origin remote_branch_name:local_branch_name
You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend
import matplotlib.pyplot as plt
plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=2, mode="expand", borderaxespad=0.)
plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
Using Request.Url.Host
is appropriate - it's how you retrieve the value of the HTTP Host:
header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858
is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority
.
Furthermore, it is not valid to get somedomain.com
from www.somedomain.com
because a webserver could be configured to serve a different site for www.somedomain.com
compared to somedomain.com
, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.')
works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config
) is a red-herring.
This will work in the latest Xcode.
-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
cell.backgroundColor = [UIColor grayColor];
}
Open "SQL Shell (psql)" from your Applications (Mac).
Click enter for the default settings. Enter the password when prompted.
*) Type \?
for help
*) Type \conninfo
to see which user you are connected as.
*) Type \l
to see the list of Databases.
*) Connect to a database by \c <Name of DB>
, for example \c GeneDB1
You should see the key prompt change to the new DB, like so:
*) Now that you're in a given DB, you want to know the Schemas for that DB. The best command to do this is \dn
.
Other commands that also work (but not as good) are select schema_name from information_schema.schemata;
and select nspname from pg_catalog.pg_namespace;
:
-) Now that you have the Schemas, you want to know the tables in those Schemas. For that, you can use the dt
command. For example \dt "GeneSchema1".*
*) Now you can do your queries. For example:
*) Here is what the above DB, Schema, and Tables look like in pgAdmin:
Put 0 as default in SQL or add 0 into your area of table
Just try this:
<button type="button">Click Me</button>
<p></p>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
});
</script>
In script.php
<?php
echo "You win";
?>
You can only use aggregates for comparison in the HAVING clause:
GROUP BY ...
HAVING SUM(cash) > 500
The HAVING
clause requires you to define a GROUP BY clause.
To get the first row where the sum of all the previous cash is greater than a certain value, use:
SELECT y.id, y.cash
FROM (SELECT t.id,
t.cash,
(SELECT SUM(x.cash)
FROM TABLE x
WHERE x.id <= t.id) AS running_total
FROM TABLE t
ORDER BY t.id) y
WHERE y.running_total > 500
ORDER BY y.id
LIMIT 1
Because the aggregate function occurs in a subquery, the column alias for it can be referenced in the WHERE clause.
These are two different modes in which your computer can operate. Prior to this, when computers were like a big room, if something crashes – it halts the whole computer. So computer architects decide to change it. Modern microprocessors implement in hardware at least 2 different states.
User mode:
Kernel mode:
How the switch occurs.
The switch from user mode to kernel mode is not done automatically by CPU. CPU is interrupted by interrupts (timers, keyboard, I/O). When interrupt occurs, CPU stops executing the current running program, switch to kernel mode, executes interrupt handler. This handler saves the state of CPU, performs its operations, restore the state and returns to user mode.
http://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode
http://tldp.org/HOWTO/KernelAnalysis-HOWTO-3.html
What I have found best is a CSRF token and save it in the session for links where you need to verify the referrer.
So if you are generating a FB callback then it would look something like this:
$token = uniqid(mt_rand(), TRUE);
$_SESSION['token'] = $token;
$url = "http://example.com/index.php?token={$token}";
Then the index.php will look like this:
if(empty($_GET['token']) || $_GET['token'] !== $_SESSION['token'])
{
show_404();
}
//Continue with the rest of code
I do know of secure sites that do the equivalent of this for all their secure pages.
shell_exec
returns all of the output stream as a string. exec
returns the last line of the output by default, but can provide all output as an array specifed as the second parameter.
See
Include an Setup Project (New Project > Other Project Types > Setup and Deployment > Visual Studio Installer
) in your solution. It has options to include the framework installer. Check out this Deployment Guide MSDN post.
How are you doing the compiling and linking? You'll need to specify both files, something like:
gcc testpoint.c point.c
...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main
. You'll need/want to eliminate one (undoubtedly the one in point.c).
In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make
to do the work. In this case you'd have something like this:
OBJS=testpoint.o point.o
testpoint.exe: $(OBJS)
gcc $(OJBS)
The first is just a macro for the names of the object files. You get it expanded with $(OBJS)
. The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.
Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:
.c.o:
$(CC) -c $(CFLAGS) $<
This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc
) and allows you to specify any flags you care about in a macro named CFLAGS
(e.g., CFLAGS=-O3
to turn on optimization) and $<
is a special macro that expands to the name of the source file.
You typically store this in a file named Makefile
, and to build your program, you just type make
at the command line. It implicitly looks for a file named Makefile
, and runs whatever rules it contains.
The good point of this is that make
automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).
Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.
First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.
If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
End If
You can do this:
([0-9]+) (\([^)]+\))? Z
This will not work with nested parens for Y, however. Nesting requires recursion which isn't strictly regular any more (but context-free). Modern regexp engines can still handle it, albeit with some difficulties (back-references).
chmod +w <directory>
or chmod a+w <directory>
- Write permission for user, group and others
chmod u+w <directory>
- Write permission for user
chmod g+w <directory>
- Write permission for group
chmod o+w <directory>
- Write permission for others
another solution , you can add <br>
tag to your table
|Method name| Behavior |
|--|--|
| OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|
Use onclick="this.value=''"
:
<input name="Name" value="Enter Your Name" onclick="this.value=''">
If you are using MS Excel 2007, you could use the conditional formatting
on the Home
tab as shown in the screenshot below. You could either use the color scales
default option as I have done here or you can go ahead and create a new rule
based on your data set.
As I outline in this other answer here on StackOverflow, you can do this by timing the download of files of various sizes (start small, ramp up if the connection seems to allow it), ensuring through cache headers and such that the file is really being read from the remote server and not being retrieved from cache. This doesn't necessarily require that you have a server of your own (the files could be coming from S3 or similar), but you will need somewhere to get the files from in order to test connection speed.
That said, point-in-time bandwidth tests are notoriously unreliable, being as they are impacted by other items being downloaded in other windows, the speed of your server, links en route, etc., etc. But you can get a rough idea using this sort of technique.
The size
attribute works, as well
<input size="25" type="text">
your panel class don't have a constructor that accepts a string
try change
RLS_strid_panel p = new RLS_strid_panel(namn1);
to
RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);
<a href="download.php?file=path/<?=$row['file_name']?>">Download</a>
download.php:
<?php
$file = $_GET['file'];
download_file($file);
function download_file( $fullPath ){
// Must be fresh start
if( headers_sent() )
die('Headers Sent');
// Required for some browsers
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// File Exists?
if( file_exists($fullPath) ){
// Parse Info / Get Extension
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
ob_clean();
flush();
readfile( $fullPath );
} else
die('File Not Found');
}
?>
Try to install gcc
and gcc-c++
, as Cmake works smooth with them.
yum install gcc gcc-c++
apt-get install cmake gcc g++
Then,
It looks like you are after the DateTime function add - use it like this:
$date = new DateTime();
date_add($date, new DateInterval("PT30M"));
(Note: untested, but according to the docs, it should work)
Please note!!! You must use the following format when instantiating PHPMailer!
$mail = new PHPMailer(true);
If you don't exceptions are ignored and the only thing you'll get is an echo from the routine! I know this is well after this was created but hopefully it will help someone.
Do as Rabbott says, or if you refuse jQuery:
<script type="text/javascript">
function get_action() { // inside script tags
return form_action;
}
</script>
<form action="" onsubmit="this.action=get_action();">
...
</form>
The following recursive function returns an array with the full list of sub directories
function getSubDirectories($dir)
{
$subDir = array();
$directories = array_filter(glob($dir), 'is_dir');
$subDir = array_merge($subDir, $directories);
foreach ($directories as $directory) $subDir = array_merge($subDir, getSubDirectories($directory.'/*'));
return $subDir;
}
Source: https://www.lucidar.me/en/web-dev/how-to-get-subdirectories-in-php/
Use this command:
egrep -lRZ "\.jpg|\.png|\.gif" . \
| xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
egrep
: find matching lines using extended regular expressions
-l
: only list matching filenames
-R
: search recursively through all given directories
-Z
: use \0
as record separator
"\.jpg|\.png|\.gif"
: match one of the strings ".jpg"
, ".gif"
or ".png"
.
: start the search in the current directory
xargs
: execute a command with the stdin as argument
-0
: use \0
as record separator. This is important to match the -Z
of egrep
and to avoid being fooled by spaces and newlines in input filenames.
-l
: use one line per command as parameter
sed
: the stream editor
-i
: replace the input file with the output without making a backup
-e
: use the following argument as expression
's/\.jpg\|\.gif\|\.png/.bmp/g'
: replace all occurrences of the strings ".jpg"
, ".gif"
or ".png"
with ".bmp"
As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang
package is automatically imported, as is everything in the current package.
The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.
By the way, if you are using lots of static methods (from Math
, for example), you could also write
import static java.lang.Math.*;
and then use
sqrt(x)
directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)
None of the answers given answer the original question.
The question is how to separate a div into 2 columns using css.
All of the above answers actually embed 2 divs into a single div in order to simulate 2 columns. This is a bad idea because you won't be able to flow content into the 2 columns in any dynamic fashion.
So, instead of the above, use a single div that is defined to contain 2 columns using CSS as follows...
.two-column-div {
column-count: 2;
}
assign the above as a class to a div, and it will actually flow its contents into the 2 columns. You can go further and define gaps between margins as well. Depending on the content of the div, you may need to mess with the word break values so your content doesn't get cut up between the columns.
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
If if doesn't work then use "!Important"
@media (min-width: 1200px) { .container { width: 970px !important; } }
If you want to set the column you filter on as a new index, you could also consider to use .filter
; if you want to keep it as a separate column then str.contains
is the way to go.
Let's say you have
df = pd.DataFrame({'vals': [1, 2, 3, 4, 5], 'ids': [u'aball', u'bball', u'cnut', u'fball', 'ballxyz']})
ids vals
0 aball 1
1 bball 2
2 cnut 3
3 fball 4
4 ballxyz 5
and your plan is to filter all rows in which ids
contains ball
AND set ids
as new index, you can do
df.set_index('ids').filter(like='ball', axis=0)
which gives
vals
ids
aball 1
bball 2
fball 4
ballxyz 5
But filter
also allows you to pass a regex, so you could also filter only those rows where the column entry ends with ball
. In this case you use
df.set_index('ids').filter(regex='ball$', axis=0)
vals
ids
aball 1
bball 2
fball 4
Note that now the entry with ballxyz
is not included as it starts with ball
and does not end with it.
If you want to get all entries that start with ball
you can simple use
df.set_index('ids').filter(regex='^ball', axis=0)
yielding
vals
ids
ballxyz 5
The same works with columns; all you then need to change is the axis=0
part. If you filter based on columns, it would be axis=1
.
LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall
# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)
test: $(SRC)
gcc -o $@ $^ $(CFLAGS) $(LIBS)
I had the very same problem as author!
To solve my issue I had to add Maven Integration Plugin: File | Settings | Plugins
Like this:
After that Intellij downloaded all the dependencies from pom.xml file.
Now if I want to create a project based on maven model, I just choose Open on the first Intellij window and choose the pom.xml file:
print df.to_string(index=False)
print(df.to_string(index=False))
If you're using MySQL:
SELECT
DATE(created) AS saledate,
SUM(amount)
FROM
Sales
GROUP BY
saledate
If you're using MS SQL 2008:
SELECT
CAST(created AS date) AS saledate,
SUM(amount)
FROM
Sales
GROUP BY
CAST(created AS date)
''.join(s[i+1]+s[i] for i in range(0, len(s), 2)) # 10.6 usec per loop
or
''.join(x+y for x, y in zip(s[1::2], s[::2])) # 10.3 usec per loop
or if the string can have an odd length:
''.join(x+y for x, y in itertools.izip_longest(s[1::2], s[::2], fillvalue=''))
Note that this won't work with old versions of Python (if I'm not mistaking older than 2.5).
The benchmark was run on python-2.7-8.fc14.1.x86_64 and a Core 2 Duo 6400 CPU with s='0123456789'*4
.
There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.
version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}" # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}" # 7 1
You can use the DirectoryInfo.GetFiles
method:
FileInfo[] files = DirectoryInfo.GetFiles("*.xml");
I know this says command line, but just a tidbit of something quick to try that might work, if you've got MySQL workbench and the csv isn't too large, you can simply
I say hope for the best because this is MySQL Workbench. You never know when it's going to explode
If you want to do this on a remote server, you would do
mysql -h<server|ip> -u<username> -p --local-infile bark -e "LOAD DATA LOCAL INFILE '<filename.csv>' INTO TABLE <table> FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"
Note, I didn't put a password after -p
as putting one on the command line is considered bad practice
When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.
In addition to the others: Merge sort is very efficient for immutable datastructures like linked lists and is therefore a good choice for (purely) functional programming languages.
A poorly implemented quicksort can be a security risk.
For having a trasition effect like a highlighter just to highlight the text and fade off the bg color, we used the following:
.field-error {_x000D_
color: #f44336;_x000D_
padding: 2px 5px;_x000D_
position: absolute;_x000D_
font-size: small;_x000D_
background-color: white;_x000D_
}_x000D_
_x000D_
.highlighter {_x000D_
animation: fadeoutBg 3s; /***Transition delay 3s fadeout is class***/_x000D_
-moz-animation: fadeoutBg 3s; /* Firefox */_x000D_
-webkit-animation: fadeoutBg 3s; /* Safari and Chrome */_x000D_
-o-animation: fadeoutBg 3s; /* Opera */_x000D_
}_x000D_
_x000D_
@keyframes fadeoutBg {_x000D_
from { background-color: lightgreen; } /** from color **/_x000D_
to { background-color: white; } /** to color **/_x000D_
}_x000D_
_x000D_
@-moz-keyframes fadeoutBg { /* Firefox */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes fadeoutBg { /* Safari and Chrome */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}_x000D_
_x000D_
@-o-keyframes fadeoutBg { /* Opera */_x000D_
from { background-color: lightgreen; }_x000D_
to { background-color: white; }_x000D_
}
_x000D_
<div class="field-error highlighter">File name already exists.</div>
_x000D_
Ctrl + MouseWheel on active editor.
Because one moderator deleted my detailed image-supported answer on this question, just because I copied and pasted from another question, I am forced to put a less detailed answer and I will link the original answer if you want a more visual way to see the solution.
For Visual Studio 2019 and Visual Studio 2017 Users
For People who are missing this old feature in VS2019 (or maybe VS2017) from the old versions of Visual Studio
This feature still available, but it is NOT available by default, you have to install it separately.
see this answer also to see an image associated
https://stackoverflow.com/a/66289543/4390133
(whish that the moderator realized this is the same question and instead of deleting my answer, he could mark one of the questions as duplicated to the other)
Update to create a class-diagram for the whole project
I received a downvote because I did not mention how to generate a diagram for the whole project, here is how to do it (after applying the previous steps)
Preview Selected Items
is enabled in the solution explorer, disabled it temporarily, you can re-enable it lateryou could be shocked by the results to the point that you can change your mind and remove your downvote (please do NOT upvote, it is enough to remove your downvote)
I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.
You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:
render: function() {
return (
<span>
// This will go through all the elements in arrayFromJson and
// render each one as a <SomeComponent /> with data from the object
{this.state.arrayFromJson.map(function(object) {
return (
<SomeComponent key={object.id} data={object} />
);
})}
</span>
);
}
I think you'll have to import the project via the file->import wizard:
http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse
It's not the last step, but it will start you on your way.
I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).
This is a two-step process:
you need to create a login to SQL Server for that user, based on its Windows account
CREATE LOGIN [<domainName>\<loginName>] FROM WINDOWS;
you need to grant this login permission to access a database:
USE (your database)
CREATE USER (username) FOR LOGIN (your login name)
Once you have that user in your database, you can give it any rights you want, e.g. you could assign it the db_datareader
database role to read all tables.
USE (your database)
EXEC sp_addrolemember 'db_datareader', '(your user name)'