(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).
In your server this line:
var data = udpServer.Receive(ref groupEP);
re-assigns groupEP
from what you had to a the address you receive something on.
This line:
udpServer.Send(new byte[] { 1 }, 1);
Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:
UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
while (true)
{
var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
var data = udpServer.Receive(ref remoteEP);
udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data
}
Also if you have server and client on the same machine you should have them on different ports.
A bit late answer, but I suggest you have a look at a not well known project on codeplex called ConferenceXP
ConferenceXP is an open source research platform that provides simple, flexible, and extensible conferencing and collaboration using high-bandwidth networks and the advanced multimedia capabilities of Microsoft Windows. ConferenceXP helps researchers and educators develop innovative applications and solutions that feature broadcast-quality audio and video in support of real-time distributed collaboration and distance learning environments.
Full source (it's huge!) is provided. It implements the RTP protocol.
They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.
One of the differences is in short
UDP : Send message and dont look back if it reached destination, Connectionless protocol
TCP : Send message and guarantee to reach destination, Connection-oriented protocol
We know that the UDP is a connection-less protocol, so it is
Specific examples:
Maybe just a bit of trivia, but UPnP will use HTTP formatted messages over UDP for device discovery.
No. Only one application can bind to a port at a time, and behavior if the bind is forced is indeterminate.
With multicast sockets -- which sound like nowhere near what you want -- more than one application can bind to a port as long as SO_REUSEADDR is set in each socket's options.
You could accomplish this by writing a "master" process, which accepts and processes all connections, then hands them off to your two applications who need to listen on the same port. This is the approach that Web servers and such take, since many processes need to listen to 80.
Beyond this, we're getting into specifics -- you tagged both TCP and UDP, which is it? Also, what platform?
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.
Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving
[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.
If you are using bash, you might as well write
echo -n "hello" >/dev/udp/localhost/8000
and avoid all the idiosyncrasies and incompatibilities of netcat.
This also works sending to other hosts, ex:
echo -n "hello" >/dev/udp/remotehost/8000
These are not "real" devices on the file system, but bash "special" aliases. There is additional information in the Bash Manual.
The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.
If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.
Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.
In the sender you set:
byte [] IP= { (byte)192, (byte)168, 1, 106 };
InetAddress address = InetAddress.getByAddress(IP);
but might be simpler to use the address in string form:
InetAddress address = InetAddress.getByName("192.168.1.106");
In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.
Here's a simple UDP Receiver that works :
import java.io.IOException;
import java.net.*;
public class Receiver {
public static void main(String[] args) {
int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
new Receiver().run(port);
}
public void run(int port) {
try {
DatagramSocket serverSocket = new DatagramSocket(port);
byte[] receiveData = new byte[8];
String sendString = "polo";
byte[] sendData = sendString.getBytes("UTF-8");
System.out.printf("Listening on udp:%s:%d%n",
InetAddress.getLocalHost().getHostAddress(), port);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
while(true)
{
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData(), 0,
receivePacket.getLength() );
System.out.println("RECEIVED: " + sentence);
// now send acknowledgement packet back to sender
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (IOException e) {
System.out.println(e);
}
// should close serverSocket in finally block
}
}
UDP is applied a lot in games or other Peer-to-peer setups because it's faster and most of the time you don't need the protocol itself to make sure everything gets to the destination in the original order (UDP does not garantee packet delivery or delivery order).
Web traffic on the other hand is over TCP. (I'm not sure here but I think it has to do with the way the HTTP protocol is built)
Edited because I failed at UDP.
Drawbacks of using TCP for live video:
FYI, please don't use the word "packages" when describing networks. Networks send "packets".
In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.
As defined in RFC 821, RFC 2821, and RFC 5321:
SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.
In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.
In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.
The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.
Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.
UDP is not "safe", so the question is not great - however -
If you send 9217 or more (mac) or 65508+ (linux/windows), the socket send function returns with an error.
The above answers discussing fragmentation and MTU and so on are off topic - that all takes place at a lower level, is "invisible" to you, and does not affect "safety" on typical connections to a significant degree.
To answer the actual question meaning though - do not use UDP - use raw sockets so you get better control of everything; since you're writing a game, you need to delve into the flags to get priority into your traffic anyhow, so you may as well get rid of UDP issues at the same time.
It is meaningless to talk about TCP or UDP without taking the network condition into account. If the network between the two point have a very high quality, UDP is absolutely faster than TCP, but in some other case such as the GPRS network, TCP may been faster and more reliability than UDP.
The MSDN is a good reference for these type of questions regarding syntax and usage. This is from the Transact SQL Reference - CASE page.
http://msdn.microsoft.com/en-us/library/ms181765.aspx
USE AdventureWorks2012;
GO
SELECT ProductNumber, Name, "Price Range" =
CASE
WHEN ListPrice = 0 THEN 'Mfg item - not for resale'
WHEN ListPrice < 50 THEN 'Under $50'
WHEN ListPrice >= 50 and ListPrice < 250 THEN 'Under $250'
WHEN ListPrice >= 250 and ListPrice < 1000 THEN 'Under $1000'
ELSE 'Over $1000'
END
FROM Production.Product
ORDER BY ProductNumber ;
GO
Another good site you may want to check out if you're using SQL Server is SQL Server Central. This has a large variety of resources available for whatever area of SQL Server you would like to learn.
find . -name "*.ear" | xargs ls -sh
I know this is old, but none of the answers here is a real solution if you want to be able to double-click Python files and have the correct interpreter used without modifying your PYTHONPATH
or PATH
every time you want to use a different interpreter. Sure, from the command line, activate my-environment
works, but OP specifically asked about double-clicking.
In this case, the correct thing to do is use the Python launcher for Windows. Then, all you have to do is add #! path\to\interpreter\python.exe
to the top of your script. Unfortunately, although the launcher comes standard with Python 3.3+, it is not included with Anaconda (see Python & Windows: Where is the python launcher?), and the simplest thing to do is to install it separately from here.
Simply wrap table tag element in a div with overflow auto and position relative. It will work in chrome and IE8. I've added height 400px in order to keep table size fixed even after reloading data.
table = $('<table cellpadding="0" cellspacing="0" border="0" class="display" id="datat"></table>').appendTo('#candidati').dataTable({
//"sScrollY": "400px",//NO MORE REQUIRED - SEE wrap BELOW
//"sScrollX": "100%",//NO MORE REQUIRED - SEE wrap BELOW
//"bScrollCollapse": true,//NO MORE REQUIRED - SEE wrap BELOW
//"bScrollAutoCss": true,//NO MORE REQUIRED - SEE wrap BELOW
"sAjaxSource": "datass.php",
"aoColumns": colf,
"bJQueryUI": true,
"sPaginationType": "two_button",
"bProcessing": true,
"bJQueryUI":true,
"bPaginate": true,
"table-layout": "fixed",
"fnServerData": function(sSource, aoData, fnCallback, oSettings) {
aoData.push({"name": "filters", "value": $.toJSON(getSearchFilters())});//inserisce i filtri
oSettings.jqXHR = $.ajax({
"dataType": 'JSON',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
});
},
"fnRowCallback": function(nRow, aData, iDisplayIndex) {
$(nRow).click(function() {
$(".row_selected").removeClass("row_selected");
$(this).addClass("row_selected");
//mostra il detaglio
showDetail(aData.CandidateID);
});
},
"fnDrawCallback": function(oSettings) {
},
"aaSorting": [[1, 'asc']]
}).wrap("<div style='position:relative;overflow:auto;height:400px;'/>"); //correzione per il disallineamento dello header
Try using ISNULL
function:
SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1
INNER JOIN Table2
ON Table1.Col1 = Table2.Col1
AND ISNULL(Table1.Col2, 'ZZZZ') = ISNULL(Table2.Col2,'ZZZZ')
Where 'ZZZZ'
is some arbitrary value never in the table.
Another option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.
org.apache.commons.lang3.StringUtils:
public static String replaceIgnoreCase(String text, String searchString, String replacement)
Case insensitively replaces all occurrences of a String within another String.
If you're on a Unix-like system, use gettimeofday
and convert the result from microseconds to milliseconds.
Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.
static class Program
{
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args[0], Convert.ToInt32(args[1])));
}
}
In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.
public Form1(string s, int i)
{
if (s != null && i > 0)
MessageBox.Show(s + " " + i);
}
To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below
C:\MyApplication>Yourexename p10 5
From the C# code above, it will prompt a Messagebox with value p10 5
.
From Microsoft documentation:
PAGEIOLATCH_SH
Occurs when a task is waiting on a latch for a buffer that is in an
I/O
request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.
In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.
If your query is like this:
Select * from <table> where <col1> = <value> order by <PrimaryKey>
, check that you have a composite index on (col1, col_primary_key)
.
If you don't have one, then you'll need either a full INDEX SCAN
if the PRIMARY KEY
is chosen, or a SORT
if an index on col1
is chosen.
Both of them are very disk I/O
consuming operations on large tables.
When you use the ShowDialog()
or Show()
method, and then close the form, the form object does not get completely destroyed (closing != destruction). It will remain alive, only it's in a "closed" state, and you can still do things to it.
you have to use capital True and False not true and false
I had the same problem with eclipse on windows 10.
I installed it like recommende over the windows command window (cmd) with:
C:\Users\NAMEOFUSER\AppData\Local\Programs\Python\beautifulsoup4-4.8.2\setup.py install
BeautifulSoup was install like this in my python directory:
C:\Users\NAMEOFUSE\AppData\Local\Programs\Python\Python38\Lib\site-packages\beautifulsoup4-4.8.2-py3.8.egg
After manually coping the bs4 and EGG-INFO folders into the site-packages folder everything started to work, also the example:
from bs4 import BeautifulSoup
html = """
<html>
<body>
<p> Ich bin ein Absatz!</p>
</body>
</html>
"""
print(html)
soup = BeautifulSoup(html, 'html.parser')
print(soup.find_all("p"))
SKU stands for Stock-keeping Unit. It's more for inventory tracking purpose.
The purpose of having an SKU is so that you can tie the app sales to whatever internal SKU number that your accounting is using.
Using the SSH URL from GitLab:
Step 1: Generate an SSH Key with default values from GitLab.
GitLab provides the commands to generate it. Just copy them, edit the email, and paste it in the terminal. Using the default values is important. Else SourceTree will not be able to access the SSH key without additional configuration.
STEP 2: Add the SSH key to your keychain using the command ssh-add -K
.
Open the terminal and paste the above command in it. This will add the key to your keychain.
STEP 3: Restart SourceTree and clone remote repo using URL.
Restarting SourceTree is needed so that SourceTree picks the new key.
STEP 4: Copy the SSH URL provided by GitLab.
STEP 5: Paste the SSH URL into the Source URL field of SourceTree.
These steps were successfully performed on Mac OS 10.13.2 using SourceTree 2.7.1.
Try the clear property.
Remember that float removes an element from the document layout - so yes, in a way it is "interfering" with br
and p
tags, in the sense that it would basically be ignoring anything in the main flow layout.
To make multiple checking statements more readable (and avoid nested ifs):
var tmp = 'Test[[email protected]]';
var posStartEmail = undefined;
var posEndEmail = undefined;
var email = undefined;
do {
if (tmp.toLowerCase().substring(0,4) !== 'test') { break; }
posStartEmail = tmp.toLowerCase().substring(4).indexOf('[');
posEndEmail = tmp.toLowerCase().substring(4).indexOf(']');
if (posStartEmail === -1 || posEndEmail === -1) { break; }
email = tmp.substring(posStartEmail+1+4,posEndEmail);
if (email.indexOf('@') === -1) { break; }
// all checks are done - do what you intend to do
alert ('All checks are ok')
break; // the most important break of them all
} while(true);
You can do it by using a formula and including the viewport width.
font-size: calc(7px + .5vw);
This sets the minimum font size at 7px and amplifies it by .5vw depending on the viewport width.
Good luck!
You have to create a new property (ex:selectedCountry) and should use it in [(ngModel)]
and further in component file assign default
value to it.
In your_component_file.ts
this.selectedCountry = default;
In your_component_template.html
<select id="country" formControlName="country" [(ngModel)]="selectedCountry">
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
//create authentication base 64 encoding string
let PasswordString = "\(txtUserName.text):\(txtPassword.text)"
let PasswordData = PasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
//let base64EncodedCredential = PasswordData!.base64EncodedStringWithOptions(nil)
//create authentication url
let urlPath: String = "http://...../auth"
var url: NSURL = NSURL(string: urlPath)
//create and initialize basic authentication request
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("Basic \(base64EncodedCredential)", forHTTPHeaderField: "Authorization")
request.HTTPMethod = "GET"
//You can use one of below methods
//1 URL request with NSURLConnectionDataDelegate
let queue:NSOperationQueue = NSOperationQueue()
let urlConnection = NSURLConnection(request: request, delegate: self)
urlConnection.start()
//2 URL Request with AsynchronousRequest
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
//2 URL Request with AsynchronousRequest with json output
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler:{ (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("\(jsonResult)")
})
//3 URL Request with SynchronousRequest
var response: AutoreleasingUnsafePointer<NSURLResponse?>=nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error:nil)
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println("\(jsonResult)")
//4 URL Request with NSURLSession
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
let session = NSURLSession(configuration: config)
session.dataTaskWithURL(url) {
(let data, let response, let error) in
if let httpResponse = response as? NSHTTPURLResponse {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}
}.resume()
// you may be get fatal error if you changed the request.HTTPMethod = "POST" when server request GET request
len
is a built-in function that calls the given container object's __len__
member function to get the number of elements in the object.
Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).
Using obj.__len__()
wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.
There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.
The other way utilizes Destructuring assignment.
let [moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown] = Array(6).fill(false);_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown_x000D_
}, null, ' '));_x000D_
_x000D_
// NOTE: If you want to do this with objects, you would be safer doing this_x000D_
let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));_x000D_
console.log(JSON.stringify({_x000D_
obj1, obj2, obj3_x000D_
}, null, ' '));_x000D_
// So that each array element is a unique object_x000D_
_x000D_
// Or another cool trick would be to use an infinite generator_x000D_
let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();_x000D_
console.log(JSON.stringify({_x000D_
a, b, c, d_x000D_
}, null, ' '));_x000D_
_x000D_
// Or generic fixed generator function_x000D_
function* nTimes(n, f) {_x000D_
for(let i = 0; i < n; i++) {_x000D_
yield f();_x000D_
}_x000D_
}_x000D_
let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];_x000D_
console.log(JSON.stringify({_x000D_
p1, p2, p3_x000D_
}, null, ' '));
_x000D_
This allows you to initialize a set of var
, let
, or const
variables to the same value on a single line all with the same expected scope.
References:
MDN: Array Global Object
MDN: Array.fill
I guess problem is in width attributes in table and td remove 'px' for example
<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">
Should be
<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">
Information on this will probably get outdated fast because Microsoft is running to complete its work on this, but as today, June 9th 2017, support to create SQL Server Integration Services (SSIS) projects on Visual Studio 2017 is not available. So, you can't see this option because so far it doesn't exist yet.
Beyond that, even installing what is being called SSDT (SQL Server Data Tools) in VS 2017 installer (what seems very confusing from Microsoft's part, using a known name for a different thing, breaking the behavior we expect as users), you won't see SQL Server Analysis Services (SSAS) and SQL Server Reporting Services (SSRS) project templates as well.
Actually, the Business Intelligence group under the Installed templates on the New Project dialog won't be present at all.
You need to go to this page (https://docs.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt) and install two separate installers, one for SSAS and one for SSRS.
Once you install at least one of these components, the Business Intelligence group will be created and the correspondent template(s) will be available. But as today, there is no installer for SSIS, so if you need to work with SSIS projects, you need to keep using SSDT 2015, for now.
Use the command as
java -classpath ".;C:\MyLibs\a\*;D:\MyLibs\b\*" <your-class-name>
The above command will set the mentioned paths to classpath only once for executing the class named TestClass.
If you want to execute more then one classes, then you can follow this
set classpath=".;C:\MyLibs\a\*;D:\MyLibs\b\*"
After this you can execute as many classes as you want just by simply typing
java <your-class-name>
The above command will work till you close the command prompt. But after closing the command prompt, if you will reopen the command prompt and try to execute some classes, then you have to again set the classpath with the help of any of the above two mentioned methods.(First method for executing one class and second one for executing more classes)
If you want to set the classpth only once so that it could work for everytime, then do as follows
1. Right click on "My Computer" icon
2. Go to the "properties"
3. Go to the "Advanced System Settings" or "Advance Settings"
4. Go to the "Environment Variable"
5. Create a new variable at the user variable by giving the information as below
a. Variable Name- classpath
b. Variable Value- .;C:\program files\jdk 1.6.0\bin;C:\MyLibs\a\';C:\MyLibs\b\*
6.Apply this and you are done.
Remember this will work every time. You don't need to explicitly set the classpath again and again.
NOTE: If you want to add some other libs after some day, then don't forget to add a semi-colon at the end of the "variable-value" of the "Environment Variable" and then type the path of your new libs after the semi-colon. Because semi-colon separates the paths of different directories.
Hope this will help you.
I found 3 ways to implement this:
C# class:
public class AddressInfo {
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
}
Action:
[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
return Json(new { success = true });
}
JavaScript you can do it three ways:
1) Query String:
$.ajax({
url: '/en/Home/Check',
data: $('#form').serialize(),
type: 'POST',
});
Data here is a string.
"Address1=blah&Address2=blah&City=blah&State=blah&ZipCode=blah&Country=blah"
2) Object Array:
$.ajax({
url: '/en/Home/Check',
data: $('#form').serializeArray(),
type: 'POST',
});
Data here is an array of key/value pairs :
=[{name: 'Address1', value: 'blah'}, {name: 'Address2', value: 'blah'}, {name: 'City', value: 'blah'}, {name: 'State', value: 'blah'}, {name: 'ZipCode', value: 'blah'}, {name: 'Country', value: 'blah'}]
3) JSON:
$.ajax({
url: '/en/Home/Check',
data: JSON.stringify({ addressInfo:{//missing brackets
Address1: $('#address1').val(),
Address2: $('#address2').val(),
City: $('#City').val(),
State: $('#State').val(),
ZipCode: $('#ZipCode').val()}}),
type: 'POST',
contentType: 'application/json; charset=utf-8'
});
Data here is a serialized JSON string. Note that the name has to match the parameter name in the server!!
='{"addressInfo":{"Address1":"blah","Address2":"blah","City":"blah","State":"blah", "ZipCode", "blah", "Country", "blah"}}'
I just wanted to illustrate that the built-in solutions (SQL-only) are not always the best ones. At first I thought that because Django's QuerySet.objects.order_by
method accepts multiple arguments, you could easily chain them:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
But, it does not work as you would expect. Case in point, first is a list of presidents sorted by score (selecting top 5 for easier reading):
>>> auths = Author.objects.order_by('-score')[:5]
>>> for x in auths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
Using Alex Martelli's solution which accurately provides the top 5 people sorted by last_name
:
>>> for x in sorted(auths, key=operator.attrgetter('last_name')): print x
...
Benjamin Harrison (467)
James Monroe (487)
Gerald Rudolph (464)
Ulysses Simpson (474)
Harry Truman (471)
And now the combined order_by
call:
>>> myauths = Author.objects.order_by('-score', 'last_name')[:5]
>>> for x in myauths: print x
...
James Monroe (487)
Ulysses Simpson (474)
Harry Truman (471)
Benjamin Harrison (467)
Gerald Rudolph (464)
As you can see it is the same result as the first one, meaning it doesn't work as you would expect.
-a option?
Cf. man page:
-a file
Attach the given file to the message.
Result:
Content-Type: text/html: No such file or directory
My new favorite alias, based on bonyiii's answer (upvoted), and my own answer about "Pass an argument to a Git alias command":
git config alias.restore '!f() { git checkout $(git rev-list -n 1 HEAD -- $1)~1 -- $(git diff --name-status $(git rev-list -n 1 HEAD -- $1)~1 | grep '^D' | cut -f 2); }; f'
I have lost a file, deleted by mistake a few commits ago?
Quick:
git restore my_deleted_file
Crisis averted.
Warning, with Git 2.23 (Q3 2019) comes the experimental command named git restore
(!).
So rename this alias (as shown below).
Robert Dailey proposes in the comments the following alias:
restore-file = !git checkout $(git rev-list -n 1 HEAD -- "$1")^ -- "$1"
And jegan adds in the comments:
For setting the alias from the command line, I used this command:
git config --global alias.restore "\!git checkout \$(git rev-list -n 1 HEAD -- \"\$1\")^ -- \"\$1\""
I've modified Foxidrive's answer to copy entire folders and all their contents. this script will create a folder and backup another folder's contents into it, including any subfolders underneath.
If you put this in say an hourly scheduled task you need to be careful as you could fill up your drive quickly with copies of your original folder. Before bitbucket etc i was using as similar script to save my code offline.
@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%
set stamp=YourPrefixHere_%YYYY%%MM%%DD%@%HH%%Min%
rem you could for example want to create a folder in Gdrive and save backup there
cd C:\YourGoogleDriveFolder
mkdir %stamp%
cd %stamp%
xcopy C:\FolderWithDataToBackup\*.* /s
In my and possibly @BIOHAZARD case it was nginx proxy timeout
. In default it's 60
sec without activity in socket
I changed it to 24h in nginx
and it resolved problem
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
Normally Python throws NameError
if the variable is not defined:
>>> d[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined
However, you've managed to stumble upon a name that already exists in Python.
Because dict
is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.
The type of dict
is a type
. All types are objects in Python. Thus you are actually trying to index into the type
object. This is why the error message says that the "'type' object is not subscriptable."
>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable
Note that you can blindly assign to the dict
name, but you really don't want to do that. It's just going to cause you problems later.
>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'
The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:
d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))
A quick search on the conda official docs will help you to find what each flag does.
So far:
-y
: Do not ask for confirmation.-f
: I think it should be --file
, so it read package versions from the given file.-q
: Do not display progress bar.-c
: Additional channel to search for packages. These are URLs searched in the orderYou can use the options when initializing the carousel, like this:
// interval is in milliseconds. 1000 = 1 second -> so 1000 * 10 = 10 seconds
$('.carousel').carousel({
interval: 1000 * 10
});
or you can use the interval
attribute directly on the HTML
tag, like this:
<div class="carousel" data-interval="10000">
The advantage of the latter approach is that you do not have to write any JS for it - while the advantage of the former is that you can compute the interval and initialize it with a variable value at run time.
I disabled Chrome extension "Coupons at Checkout" and this problem was solved.
As you didn't give us very much information, I'm assuming the language you're writing the code in is C#. First of all: Prefer System.Collections.Generic.List over an ArrayList. Secondly: One way would be to loop through every item in the list and check whether it contains "How". Another way would be to use LINQ. Here's a quick example that filters out every item which doesn't contain "How":
var list = new List<string>();
list.AddRange(new string[] {
"How are you?",
"How you doing?",
"Joe",
"Mike", });
foreach (string str in list.Where(s => s.Contains("How")))
{
Console.WriteLine(str);
}
Console.ReadLine();
Check the service name of a database by
sql> show parameter service;
In c++ strings are not first class citizens. The string operations are done through standard library. I think, that is the reason. Also, C++ uses branch table optimization to optimize the switch case statements. Have a look at the link.
This should work for any table, instead of hard-coding the columns.
//Source details_x000D_
String sourceUrl = "jdbc:oracle:thin:@//server:1521/db";_x000D_
String sourceUserName = "src";_x000D_
String sourcePassword = "***";_x000D_
_x000D_
// Destination details_x000D_
String destinationUserName = "dest";_x000D_
String destinationPassword = "***";_x000D_
String destinationUrl = "jdbc:mysql://server:3306/db";_x000D_
_x000D_
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);_x000D_
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);_x000D_
_x000D_
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");_x000D_
ResultSet rs = sourceStatement.executeQuery();_x000D_
rs.setFetchSize(1000); // not needed_x000D_
_x000D_
_x000D_
ResultSetMetaData meta = rs.getMetaData();_x000D_
_x000D_
_x000D_
_x000D_
List<String> columns = new ArrayList<>();_x000D_
for (int i = 1; i <= meta.getColumnCount(); i++)_x000D_
columns.add(meta.getColumnName(i));_x000D_
_x000D_
try (PreparedStatement destStatement = destConnection.prepareStatement(_x000D_
"INSERT INTO dest_table ("_x000D_
+ columns.stream().collect(Collectors.joining(", "))_x000D_
+ ") VALUES ("_x000D_
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))_x000D_
+ ")"_x000D_
)_x000D_
)_x000D_
{_x000D_
int count = 0;_x000D_
while (rs.next()) {_x000D_
for (int i = 1; i <= meta.getColumnCount(); i++) {_x000D_
destStatement.setObject(i, rs.getObject(i));_x000D_
}_x000D_
_x000D_
destStatement.addBatch();_x000D_
count++;_x000D_
}_x000D_
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed_x000D_
System.out.println("done " + count);_x000D_
_x000D_
}
_x000D_
For those using npm to install packages, you can install jquery via npm install jquery
and then use elixir to compile jquery and your other npm packages into one file (e.g. vendor.js). Here's a sample gulpfile.js
var elixir = require('laravel-elixir');
elixir(function(mix) {
mix
.scripts([
'jquery/dist/jquery.min.js',
// list your other npm packages here
],
'public/js/vendor.js', // 2nd param is the output file
'node_modules') // 3rd param is saying "look in /node_modules/ for these scripts"
.scripts([
'scripts.js' // your custom js file located in default location: /resources/assets/js/
], 'public/js/app.js') // looks in default location since there's no 3rd param
.version([ // optionally append versioning string to filename
'js/vendor.js', // compiled files will be in /public/build/js/
'js/app.js'
]);
});
It's still valid to use IE=edge,chrome=1.
But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.
I use the following for correctness nowadays
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
Another memory tool for your list: Memory Validator.
Not free, but nowhere near as expensive as Purify or Boundschecker.
For viewers who got this error after upgrading React Native to 0.40+, you may need to run react-native upgrade
on the command line.
You'll need to make a list of the keys, sort them according to the corresponding values, then iterate over the sorted keys.
Map<String, String> map = getMyMap();
List<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys, someComparator);
for (String key: keys) {
System.out.println(key + ": " + map.get(key));
}
As for what to use for someComparator
, here are some handy, generic Comparator-creating routines I often find useful. The first one sorts by the values according to their natural ordering, and the second allows you to specify any arbitrary Comparator to sort the values:
public static <K, V extends Comparable<? super V>>
Comparator<K> mapValueComparator(final Map<K, V> map) {
return new Comparator<K>() {
public int compare(K key1, K key2) {
return map.get(key1).compareTo(map.get(key2));
}
};
}
public static <K, V>
Comparator<K> mapValueComparator(final Map<K, V> map,
final Comparator<V> comparator) {
return new Comparator<K>() {
public int compare(K key1, K key2) {
return comparator.compare(map.get(key1), map.get(key2));
}
};
}
I was able to fix this!
Had the same problems as stated above, made sure nothing was using port 80 and still not working and getting the message that Apache and Mysql were detected with the wrong path.
I did install XAMPP once before, uninstalled and reinstalled. I even manually uninstalled but still had issues.
The fix. Make sure you backup your system first!
Start Services via Control Panel>Admin Tools (also with Ctrl+R and services.msc
)
Look for Apache and MySQL services. Look at the patch indicated in the description (right click on service then click on properties). Chances are that you have Apache listed twice, one from your correct install and one from a previous install. Even if you only see one, look at the path, chances are it's from a previous install and causing your install not to work. In either case, you need to delete those incorrect services.
a. Got to command prompt (run as administrator): Start > all programs > Accessories > right click on Command Prompt > Select 'run as administrator'
b. on command prompt type sc delete service
, where service is the service you're wanting to delete, such as apache2.1 (or sc delete Apache2.4
). It should be exactly as it appears in your services. If the service has spaces such as Apache 2.1 then enter it in quotes, i.e. sc delete "Apache 2.1"
c. press enter. Now refresh or close/open your services window and you'll see it`s gone.
DO THIS for all services that XAMPP finds as running with an incorrect path.
Once you do this, go ahead and restart the XAMPP control panel (as administrator) and voila! all works. No conflicts
This can be done in two ways.
JLabel Horizontal Alignment
You can use the JLabel
constructor:
JLabel(String text, int horizontalAlignment)
To align to the right:
JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);
JLabel
also has setHorizontalAlignment
:
label.setHorizontalAlignment(SwingConstants.RIGHT);
This assumes the component takes up the whole width in the container.
Using Layout
A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout
:
Box box = Box.createVerticalBox();
JLabel label1 = new JLabel("test1, the beginning");
label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label1);
JLabel label2 = new JLabel("test2, some more");
label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label2);
JLabel label3 = new JLabel("test3");
label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label3);
add(box);
This might be useful for someone else: Using this sample html
<div class="ParentDiv">
<label for="label">labelName</label>
<input type="button" value="elementToSelect">
</div>
<div class="DontSelect">
<label for="animal">pig</label>
<input type="button" value="elementToSelect">
</div>
If for example, I want to select an element in the same section (e.g div) as a label, you can use this
//label[contains(., 'labelName')]/parent::*//input[@value='elementToSelect']
This just means, look for a label (it could anything like a
, h2
) called labelName
. Navigate to the parent of that label (i.e. div class="ParentDiv"
). Search within the descendants of that parent to find any child element with the value of elementToSelect
. With this, it will not select the second elementToSelect
with DontSelect
div as parent.
The trick is that you can reduce search areas for an element by navigating to the parent first and then searching descendant of that parent for the element you need.
Other Syntax like following-sibling::h2
can also be used in some cases. This means the sibling following element h2
. This will work for elements at the same level, having the same parent.
But you could make an own link for every from url.
Example: http://example.com?auth=holasite
In this example your site is: example.com
If somebody open that link it's give you the holasite value for the auth variable.
Then just $_GET['auth'] and you have the variable. But you should have a database to store it, and to authorize.
Like: $holasite = http://holasite.com (You could use mysql too..)
And just match it, and you have the url.
This method is a little bit more complicated, but it works. This method is good for a referral system authentication. But where is the site name, you should write an id, and works with that id.
Like bruno said, you're better configuring it yourself. Here's how I do it. Start by creating a properties file (/etc/myapp/config.properties).
javax.net.ssl.keyStore = /etc/myapp/keyStore
javax.net.ssl.keyStorePassword = 123456
Then load the properties to your environment from your code. This makes your application configurable.
FileInputStream propFile = new FileInputStream("/etc/myapp/config.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
System.setProperties(p);
You said that you can’t use HTML comments because the CMS filters them out. So I assume that you really want to hide this content and you don’t need to display it ever.
In that case, you shouldn’t use CSS (only), as you’d only play on the presentation level, not affecting the content level. Your content should also be hidden for user-agents ignoring the CSS (people using text browsers, feed readers, screen readers; bots; etc.).
In HTML5 there is the global hidden
attribute:
When specified on an element, it indicates that the element is not yet, or is no longer, directly relevant to the page's current state, or that it is being used to declare content to be reused by other parts of the page as opposed to being directly accessed by the user. User agents should not render elements that have the
hidden
attribute specified.
Example (using the small
element here, because it’s an "attribution"):
<small hidden>Thanks to John Doe for this idea.</small>
As a fallback (for user-agents that don’t know the hidden
attribute), you can specify in your CSS:
[hidden] {display:none;}
An general element for plain text could be the script
element used as "data block":
<script type="text/plain" hidden>
Thanks to John Doe for this idea.
</script>
Alternatively, you could also use data-*
attributes on existing elements (resp. on new div
elements if you want to group some elements for the attribution):
<p data-attribution="Thanks to John Doe for this idea!">This is some visible example content …</p>
string[] MultiEmails = email.Split(',');
foreach (string ToEmail in MultiEmails)
{
message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
}
An easier way is to use the heredoc syntax of PHP. An example:
<?php
echo <<<EOF
<script type="text/javascript">
document.write("Hello World!");
</script>
EOF;
?>
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Then all operations performed using the aGMTCalendar object will be done with the GMT time zone and will not have the daylight savings time or fixed offsets applied
Wrong!
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.getTime(); //or getTimeInMillis()
and
Calendar aNotGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));aNotGMTCalendar.getTime();
will return the same time. Idem for
new Date(); //it's not GMT.
Its really working if we use Doctype on our web page jquery(window) will return the viewport height else it will return the complete document height.
Define the following tag on the top of your web page:
<!DOCTYPE html>
Fix for iPhone X/XS screen rotation issue
On iPhone X/XS, a screen rotation will cause the header bar height to use an incorrect value, because the calculation of safe-area-inset-* was not reflecting the new values in time for UI refresh. This bug exists in UIWebView even in the latest iOS 12. A workaround is inserting a 1px top margin and then quickly reversing it, which will trigger safe-area-inset-* to be re-calculated immediately. A somewhat ugly fix but it works if you have to stay with UIWebView for one reason or another.
window.addEventListener("orientationchange", function() {_x000D_
var originalMarginTop = document.body.style.marginTop;_x000D_
document.body.style.marginTop = "1px";_x000D_
setTimeout(function () {_x000D_
document.body.style.marginTop = originalMarginTop;_x000D_
}, 100);_x000D_
}, false);
_x000D_
The purpose of the code is to cause the document.body.style.marginTop to change slightly and then reverse it. It doesn't necessarily have to be "1px". You can pick a value that doesn't cause your UI to flicker but achieves its purpose.
The only thin you have to change is to use property "params" rather than "data" when you create your $http object:
$http({
method: 'POST',
url: serviceUrl + '/ClientUpdate',
params: { LangUserId: userId, clientJSON: clients[i] },
})
In the example above clients[i] is just JSON object (not serialized in any way). If you use "params" rather than "data" angular will serialize the object for you using $httpParamSerializer: https://docs.angularjs.org/api/ng/service/$httpParamSerializer
You can separate multiple classes with the space:
$("p").addClass("myClass yourClass");
You can't selectively escape %
, as %
always has a special meaning depending on the following character.
In the documentation of Python, at the bottem of the second table in that section, it states:
'%' No argument is converted, results in a '%' character in the result.
Therefore you should use:
selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
(please note the expicit change to tuple as argument to %
)
Without knowing about the above, I would have done:
selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
with the knowledge you obviously already had.
I don't think you can set arbitrarily sized images on any of the existing button classes. If you want a simple image behaving like a button, you can write your own QAbstractButton-subclass, something like:
class ImageButton : public QAbstractButton {
Q_OBJECT
public:
...
void setPixmap( const QPixmap& pm ) { m_pixmap = pm; update(); }
QSize sizeHint() const { return m_pixmap.size(); }
protected:
void paintEvent( QPaintEvent* e ) {
QPainter p( this );
p.drawPixmap( 0, 0, m_pixmap );
}
};
For Query parameters like domain.com/test?format=json&type=mini
format, then you can easily receive it via - req.query.
app.get('/test', function(req, res){
var format = req.query.format,
type = req.query.type;
});
These two terms differentiate between two different ways of walking a tree.
It is probably easiest just to exhibit the difference. Consider the tree:
A
/ \
B C
/ / \
D E F
A depth first traversal would visit the nodes in this order
A, B, D, C, E, F
Notice that you go all the way down one leg before moving on.
A breadth first traversal would visit the node in this order
A, B, C, D, E, F
Here we work all the way across each level before going down.
(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)
Both kinds of traversal can be achieved with the pseudocode:
Store the root node in Container
While (there are nodes in Container)
N = Get the "next" node from Container
Store all the children of N in Container
Do some work on N
The difference between the two traversal orders lies in the choice of Container
.
The recursive implementation looks like
ProcessNode(Node)
Work on the payload Node
Foreach child of Node
ProcessNode(child)
/* Alternate time to work on the payload Node (see below) */
The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.
At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:
D, B, E, F, C, A
which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.
This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.
The return
exits the current function, but the iterations keeps on, so you get the "next" item that skips the if
and alerts the 4...
If you need to stop the looping, you should just use a plain for
loop like so:
$('button').click(function () {
var arr = [1, 2, 3, 4, 5];
for(var i = 0; i < arr.length; i++) {
var n = arr[i];
if (n == 3) {
break;
}
alert(n);
})
})
You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp
I found that using the tornado
package to be the fastest and simplest way to achieve this:
from tornado import ioloop, httpclient, gen
def main(urls):
"""
Asynchronously download the HTML contents of a list of URLs.
:param urls: A list of URLs to download.
:return: List of response objects, one for each URL.
"""
@gen.coroutine
def fetch_and_handle():
httpclient.AsyncHTTPClient.configure(None, defaults=dict(user_agent='MyUserAgent'))
http_client = httpclient.AsyncHTTPClient()
waiter = gen.WaitIterator(*[http_client.fetch(url, raise_error=False, method='HEAD')
for url in urls])
results = []
# Wait for the jobs to complete
while not waiter.done():
try:
response = yield waiter.next()
except httpclient.HTTPError as e:
print(f'Non-200 HTTP response returned: {e}')
continue
except Exception as e:
print(f'An unexpected error occurred querying: {e}')
continue
else:
print(f'URL \'{response.request.url}\' has status code <{response.code}>')
results.append(response)
return results
loop = ioloop.IOLoop.current()
web_pages = loop.run_sync(fetch_and_handle)
return web_pages
my_urls = ['url1.com', 'url2.com', 'url100000.com']
responses = main(my_urls)
print(responses[0])
Filter the version number.
java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
in javascript, object properties can be accessed with . operator or with associative array indexing using []. ie. object.property
is equivalent to object["property"]
this should do the trick
var smth = mydata.list[0]["points.bean.pointsBase"][0].time;
If you add double paranthesis to the ngModel reference you get a two-way binding to your model property. That property can then be read and used in the event handler. In my view that is the most clean approach.
<input type="checkbox" [(ngModel)]="myModel.property" (ngModelChange)="processChange()" />
Understanding Static concepts
public class StaticPractise1 {
public static void main(String[] args) {
StaticPractise2 staticPractise2 = new StaticPractise2();
staticPractise2.printUddhav(); //true
StaticPractise2.printUddhav(); /* false, because printUddhav() is although inside StaticPractise2, but it is where exactly depends on PC program counter on runtime. */
StaticPractise2.printUddhavsStatic1(); //true
staticPractise2.printUddhavsStatic1(); /*false, because, when staticPractise2 is blueprinted, it tracks everything other than static things and it organizes in its own heap. So, class static methods, object can't reference */
}
}
Second Class
public class StaticPractise2 {
public static void printUddhavsStatic1() {
System.out.println("Uddhav");
}
public void printUddhav() {
System.out.println("Uddhav");
}
}
Another solution that takes into account possibly interleaving TEXT and ELEMENT nodes, e.g.:
<parent>
text1
<child1/>
text2
<child2/>
</parent>
Code:
using System.Linq;
namespace System.Xml.Linq
{
public static class XElementTransformExtensions
{
public static XElement WithoutNamespaces(this XElement source)
{
return new XElement(source.Name.LocalName,
source.Attributes().Select(WithoutNamespaces),
source.Nodes().Select(WithoutNamespaces)
);
}
public static XAttribute WithoutNamespaces(this XAttribute source)
{
return !source.IsNamespaceDeclaration
? new XAttribute(source.Name.LocalName, source.Value)
: default(XAttribute);
}
public static XNode WithoutNamespaces(this XNode source)
{
return
source is XElement
? WithoutNamespaces((XElement)source)
: source;
}
}
}
An alternate is to use a new helper function which will take values from List and update in the DataGridView as following:
private void DisplayStringListInDataGrid(List<string> passedList, ref DataGridView gridToUpdate, string newColumnHeader)
{
DataTable gridData = new DataTable();
gridData.Columns.Add(newColumnHeader);
foreach (string listItem in passedList)
{
gridData.Rows.Add(listItem);
}
BindingSource gridDataBinder = new BindingSource();
gridDataBinder.DataSource = gridData;
dgDataBeingProcessed.DataSource = gridDataBinder;
}
Then we can call this function the following way:
DisplayStringListInDataGrid(<nameOfListWithStrings>, ref <nameOfDataGridViewToDisplay>, <nameToBeGivenForTheNewColumn>);
Please use this profile
<profiles>
<profile>
<repositories>
<repository>
<id>mvnrepository</id>
<name>mvnrepository</name>
<url>http://www.mvnrepository.com</url>
</repository>
</repositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>mvnrepository</activeProfile>
</activeProfiles>
You can use the expandable list view explained in API demos to show groups
To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.
Try avoiding unnecessary loops and go for this if needed.
string SearchByColumn = "ColumnName=" + value;
DataRow[] hasRows = currentDataTable.Select(SearchByColumn);
if (hasRows.Length == 0)
{
//your logic goes here
}
else
{
//your logic goes here
}
If you want to search by specific ID then there should be a primary key in a table.
public void showNotification (String from, String notification, Intent intent) {
PendingIntent pendingIntent = PendingIntent.getActivity(
context,
Notification_ID,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
);
String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_DEFAULT);
// Configure the notification channel.
notificationChannel.setDescription("Channel description");
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
notificationChannel.enableVibration(true);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification mNotification = builder
.setContentTitle(from)
.setContentText(notification)
// .setTicker("Hearty365")
// .setContentInfo("Info")
// .setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
// .setDefaults(Notification.DEFAULT_ALL)
// .setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.build();
notificationManager.notify(/*notification id*/Notification_ID, mNotification);
}
Try this code that uses datetime.utcnow():
from datetime import datetime
datetime.utcnow()
For your purposes when you need to calculate an amount of time spent between two dates all that you need is to substract end and start dates. The results of such substraction is a timedelta object.
From the python docs:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
And this means that by default you can get any of the fields mentioned in it's definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks. Also timedelta instance has total_seconds() method that:
Return the total number of seconds contained in the duration. Equivalent to (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10*6) / 10*6 computed with true division enabled.
I want to point out that in PHP there is no such thing like empty object in sense:
$obj = new stdClass();
var_dump(empty($obj)); // bool(false)
but of course $obj will be empty.
On other hand empty array mean empty in both cases
$arr = array();
var_dump(empty($arr));
Quote from changelog function empty
Objects with no properties are no longer considered empty.
UserSelect =null
AlertDialog.Builder builder = new Builder(ImonaAndroidApp.LoginScreen);
builder.setMessage("you message");
builder.setPositiveButton("OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UserSelect = true ;
}
});
builder.setNegativeButton("Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
UserSelect = false ;
}
});
// in UI thread
builder.show();
// wait until the user select
while(UserSelect ==null);
Both means "every item in a set of two things". The two things being "left" and "right"
To check if a directory exists with the new IO:
if (Files.isDirectory(Paths.get("directory"))) {
...
}
isDirectory
returns true
if the file is a directory; false
if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.
See: documentation.
You mean something like this?
<?php
$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);
foreach ( $json_output->trends as $trend )
{
echo "{$trend->name}\n";
}
(T)Activator.CreateInstance(typeof(T), param1, param2);
You should be able to do something like this in your respond_to
block:
respond_to do |format|
format.json
render :partial => "users/show.json"
end
which will render the template in app/views/users/_show.json.erb
.
Let's go straight to your question.
Finding the source code for built-in Python functions?
The source code is located at Python/bltinmodule.c
To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>
, for instance, sorted()
is implemented in builtin_sorted
.
For your pleasure I'll post the implementation of sorted()
:
builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
PyObject *newlist, *v, *seq, *callable;
/* Keyword arguments are passed through list.sort() which will check
them. */
if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
return NULL;
newlist = PySequence_List(seq);
if (newlist == NULL)
return NULL;
callable = _PyObject_GetAttrId(newlist, &PyId_sort);
if (callable == NULL) {
Py_DECREF(newlist);
return NULL;
}
assert(nargs >= 1);
v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
Py_DECREF(callable);
if (v == NULL) {
Py_DECREF(newlist);
return NULL;
}
Py_DECREF(v);
return newlist;
}
As you may have noticed, that's not Python code, but C code.
Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
If this is something you are only going to need to do once, have you considered downloading a demo version of Crystal? There's a 30-day trial version available here: http://www.developers.net/businessobjectsshowcase/view/3154
Of course, if you need to edit these files after the 30 day period is over, you would be better off buying Crystal.
Alternatively, if all you need to do is replace a few static literal words, have you tried doing a search and replace in a text editor? (Don't forget to save the original files somewhere safe first!)
You can now use json.net. Just go on Nuget and install it.
And you can do something like this:
public bool Equals(SamplesItem sampleToCompare)
{
string myself = JsonConvert.SerializeObject(this);
string other = JsonConvert.SerializeObject(sampleToCompare);
return myself == other;
}
You could perhaps make a extension method for object if you wanted to get fancier. Please note this only compares the public properties. And if you wanted to ignore a public property when you do the comparison you could use the [JsonIgnore] attribute.
You can have a regular Python module, say config.py, like this:
truck = dict(
color = 'blue',
brand = 'ford',
)
city = 'new york'
cabriolet = dict(
color = 'black',
engine = dict(
cylinders = 8,
placement = 'mid',
),
doors = 2,
)
and use it like this:
import config
print(config.truck['color'])
use array.splice
/*array.splice(index , howMany[, element1[, ...[, elementN]]])
array.splice(index) // SpiderMonkey/Firefox extension*/
array.splice(1,1)
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
New operators are currently being added to the browsers, ??=
, ||=
, and &&=
. This post will focus on ??=
.
This checks if left side is undefined
or null
, short-circuiting if already defined. If not, the right-side is assigned to the left-side variable.
// Using ??=
name ??= "Dave"
// Previously, ES2020
name = name ?? "Dave"
// Before that (not equivalent, but commonly used)
name = name || "Dave" // name ||= "Dave"
let a // undefined
let b = null
let c = false
a ??= true // true
b ??= true // true
c ??= true // false
// Equivalent to
a = a ?? true
let x = ["foo"]
let y = { foo: "fizz" }
x[0] ??= "bar" // "foo"
x[1] ??= "bar" // "bar"
y.foo ??= "buzz" // "fizz"
y.bar ??= "buzz" // "buzz"
x // Array [ "foo", "bar" ]
y // Object { foo: "fizz", bar: "buzz" }
??= Browser Support Jan 2021 - 81%
easy way is:
a = [1,2]
d = {}
for i in a:
d[i]=[i, ]
print(d)
{'1': [1, ], '2':[2, ]}
You should check type of received parameters. Maybe you should use arguments
array since second parameter can sometimes be 'parameters' and sometimes 'callback' and naming it parameters might be misleading.
Do you mean
.*
.
any character, except newline character, with dotall mode it includes also the newline characters
*
any amount of the preceding expression, including 0 times
Merging json objects is fairly straight forward but has a few edge cases when dealing with key collisions. The biggest issues have to do with one object having a value of a simple type and the other having a complex type (Array or Object). You have to decide how you want to implement that. Our choice when we implemented this for json passed to chef-solo was to merge Objects and use the first source Object's value in all other cases.
This was our solution:
from collections import Mapping
import json
original = json.loads(jsonStringA)
addition = json.loads(jsonStringB)
for key, value in addition.iteritems():
if key in original:
original_value = original[key]
if isinstance(value, Mapping) and isinstance(original_value, Mapping):
merge_dicts(original_value, value)
elif not (isinstance(value, Mapping) or
isinstance(original_value, Mapping)):
original[key] = value
else:
raise ValueError('Attempting to merge {} with value {}'.format(
key, original_value))
else:
original[key] = value
You could add another case after the first case to check for lists if you want to merge those as well, or for specific cases when special keys are encountered.
So I worked out at the end that you cannot uninstall 3.4 as it is default on Ubuntu.
All I did was simply remove Jupyter
and then alias python=python2.7
and install all packages on Python 2.7 again.
Arguably, I can install virtualenv
but me and my colleagues are only using 2.7. I am just going to be lazy in this case :)
df.index[df.LastName == 'Smith']
Or
df.query('LastName == "Smith"').index
Will return all row indices where LastName
is Smith
Int64Index([1], dtype='int64')
I had a similar problem where the R.java file was not being regenerated after I'd added some icons and layout files. I tried cleaning and rebuilding and things got worse since then the original R.java file was gone and still wasn't regenerated. Eventually it dawned on me that there must be compiler errors for the compiler that generates R.java and we aren't being shown those in the console. Fortunately, I had noticed earlier that
Anyways, after renaming my icons and .xml files to all lowercase and then fixing all the references inside the .xml files, voila, R.java was regenerated. Just in time to feel good when I stopped for lunch :-)
One Lazy and Simple Solution
Assume your regex pattern is split_pattern = r'(!|\?)'
First, you add some same character as the new separator, like '[cut]'
new_string = re.sub(split_pattern, '\\1[cut]', your_string)
Then you split the new separator, new_string.split('[cut]')
You can't do it from the command line, you have to write some code (I assume you're not just looking for an utility otherwise Super User may be a better place to ask). I also assume your application has all the required permissions to do it (examples are without any error checking).
First get all the threads of a given process then call the SuspendThread
function to stop each one (and ResumeThread
to resume). It works but some applications may crash or hung because a thread may be stopped in any point and the order of suspend/resume is unpredictable (for example this may cause a dead lock). For a single threaded application this may not be an issue.
void suspend(DWORD processId)
{
HANDLE hThreadSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);
THREADENTRY32 threadEntry;
threadEntry.dwSize = sizeof(THREADENTRY32);
Thread32First(hThreadSnapshot, &threadEntry);
do
{
if (threadEntry.th32OwnerProcessID == processId)
{
HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE,
threadEntry.th32ThreadID);
SuspendThread(hThread);
CloseHandle(hThread);
}
} while (Thread32Next(hThreadSnapshot, &threadEntry));
CloseHandle(hThreadSnapshot);
}
Please note that this function is even too much naive, to resume threads you should skip threads that was suspended and it's easy to cause a dead-lock because of suspend/resume order. For single threaded applications it's prolix but it works.
Starting from Windows XP there is the NtSuspendProcess
but it's undocumented. Read this post for a code example (reference for undocumented functions: news://comp.os.ms-windows.programmer.win32).
typedef LONG (NTAPI *NtSuspendProcess)(IN HANDLE ProcessHandle);
void suspend(DWORD processId)
{
HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId));
NtSuspendProcess pfnNtSuspendProcess = (NtSuspendProcess)GetProcAddress(
GetModuleHandle("ntdll"), "NtSuspendProcess");
pfnNtSuspendProcess(processHandle);
CloseHandle(processHandle);
}
To suspend a program is what usually a debugger does, to do it you can use the DebugActiveProcess
function. It'll suspend the process execution (with all threads all together). To resume you may use DebugActiveProcessStop
.
This function lets you stop a process (given its Process ID), syntax is very simple: just pass the ID of the process you want to stop et-voila. If you'll make a command line application you'll need to keep its instance running to keep the process suspended (or it'll be terminated). See the Remarks section on MSDN for details.
void suspend(DWORD processId)
{
DebugActiveProcess(processId);
}
As I said Windows command line has not any utility to do that but you can invoke a Windows API function from PowerShell. First install Invoke-WindowsApi script then you can write this:
Invoke-WindowsApi "kernel32" ([bool]) "DebugActiveProcess" @([int]) @(process_id_here)
Of course if you need it often you can make an alias
for that.
This is how Adding new column to Table
ALTER TABLE [tableName]
ADD ColumnName Datatype
E.g
ALTER TABLE [Emp]
ADD Sr_No Int
And If you want to make it auto incremented
ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL
It will be approximately 37% larger:
Very roughly, the final size of Base64-encoded binary data is equal to 1.37 times the original data size
Packets and Frames are the names given to Protocol data units (PDUs) at different network layers
Segments/Datagrams are units of data in the Transport Layer.
In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):
Datagram
A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.
Packets are units of data in the Network Layer (IP in case of the Internet)
Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).
It is safer and more flexible to load the assembly into its own AppDomain
first.
So instead of the answer given previously:
var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
I would suggest the following (adapted from this answer to a related question):
var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
Now you can unload the assembly and have different security settings.
If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the System.AddIn
namespace). For more information, see this article on Add-ins and Extensibility on MSDN.
git commit -a -m "Your commit message here"
will quickly commit all changes with the commit message. Git commit "title" and "description" (as you call them) are nothing more than just the first line, and the rest of the lines in the commit message, usually separated by a blank line, by convention. So using this command will just commit the "title" and no description.
If you want to commit a longer message, you can do that, but it depends on which shell you use.
In bash the quick way would be:
git commit -a -m $'Commit title\n\nRest of commit message...'
I was looking for an easier method than i'm using but it isn't answered in this post. However, my method works and i don't use any of the aforementioned methods:
function MyFunction() {
$lookyHere = array(
'value1' => array('valuehere'),
'entry2' => array('valuehere')
);
return $lookyHere;
}
I have no problems with my function. I read the data in a loop to display my associated data. I have no idea why anyone would suggest the above methods. If you are looking to store multiple arrays in one file but not have all of them loaded, then use my function method above. Otherwise, all of the arrays will load on the page, thus, slowing down your site. I came up with this code to store all of my arrays in one file and use individual arrays when needed.
According to the grammar in the CSP spec, you need to specify schemes as scheme:
, not just scheme
. So, you need to change the image source directive to:
img-src 'self' data:;
For those who want some background info, here's a short article explaining why overflow: hidden
works. It has to do with the so-called block formatting context. This is part of W3C's spec (ie is not a hack) and is basically the region occupied by an element with a block-type flow.
Every time it is applied, overflow: hidden
creates a new block formatting context. But it's not the only property capable of triggering that behaviour. Quoting a presentation by Fiona Chan from Sydney Web Apps Group:
- float: left / right
- overflow: hidden / auto / scroll
- display: table-cell and any table-related values / inline-block
- position: absolute / fixed
Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent
attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)
Instead, the best approach would be to:
To allow each panel to toggle individually, on the data-toggle="collapse"
element, set the data-target
attribute to the .collapse
panel ID selector (instead of setting the data-parent
attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.
Roughly, each panel should look like this:
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"
data-toggle="collapse"
data-target="#collapseOne">
Collapsible Group Item #1
</h4>
</div>
<div id="collapseOne"
class="panel-collapse collapse">
<div class="panel-body"></div>
</div>
</div>
To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:
$('#accordion').on('show.bs.collapse', function () {
if (active) $('#accordion .in').collapse('hide');
});
Then use show
and hide
to toggle the visibility of each of the panels and data-toggle
to enable and disable the controls.
$('#collapse-init').click(function () {
if (active) {
active = false;
$('.panel-collapse').collapse('show');
$('.panel-title').attr('data-toggle', '');
$(this).text('Enable accordion behavior');
} else {
active = true;
$('.panel-collapse').collapse('hide');
$('.panel-title').attr('data-toggle', 'collapse');
$(this).text('Disable accordion behavior');
}
});
This is an error that you see when your emulator has the "Use host GPU" setting checked. If you uncheck it then the error goes away. Of course, then your emulator is not as responsive anymore.
MySQL documentation covers this topic.
Here is a synopsis. When using join
or inner join
, the on
condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join
. Similarly, you can use an on
clause with cross join
, which also differs from standard SQL.
A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.
In practice, if you want to do a cross join, then use cross join
:
from A cross join B
is much better than:
from A, B
and:
from A join B -- with no on clause
The on
clause is required for a right or left outer join, so the discussion is not relevant for them.
If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.
You can use ARG
- see https://docs.docker.com/engine/reference/builder/#arg
The
ARG
instruction defines a variable that users can pass at build-time to the builder with thedocker build
command using the--build-arg <varname>=<value>
flag. If a user specifies a build argument that was not defined in the Dockerfile, the build outputs an error.
If the run method ends, the thread will end.
If you use a loop, a proper way is like following:
// In your imlemented Runnable class:
private volatile boolean running = true;
public void run()
{
while (running)
{
...
}
}
public void stopRunning()
{
running = false;
}
Of course returning is the best way.
dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();
If you are using ASP.NET, the server-side code tags in these examples below will provide the exact control ID, even if you are using Master pages.
Javascript:
document.getElementById("<%=MyControlName.ClientID%>").value;
JQuery:
$("#<%= MyControlName.ClientID %>").val();
Insert a dummy record into one of your databases that has a timestamp Select that record and get value of timestamp. Delete that record. Gets for sure the timezone that the server is using to write data and ignores PHP timezones.
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
that scp command must be issued on the local command-line, for putty the command is pscp.
C:\something> pscp [email protected]:/dir/of/file.txt \local\dir\
package com.app;
public class SiftNumberAndEvenNumber {
public static void main(String[] args) {
int arr[] = {1,2,3,4,5};
int arr1[] = new int[arr.length];
int shiftAmount=3;
for(int i = 0; i < arr.length; i++){
int newLocation = (i + (arr.length - shiftAmount)) % arr.length;
arr1[newLocation] = arr[i];
}
for(int i=0;i<arr1.length;i++) {
if(i==arr1.length-1) {
System.out.print(arr1[i]);
}else {
System.out.print(arr1[i]+",");
}
}
System.out.println();
for(int i=0;i<arr1.length;i++) {
if(arr1[i]%2==0) {
System.out.print(arr1[i]+" ");
}
}
}
}
In my case, it was unable to find the .eslintrc
file so I copied from node_modules/.bin to root.
Import jquery (I installed with 'npm install [email protected]')
import 'jquery/jquery.js';
Put all your code that depends on jquery inside this method
+function ($) {
// your code
}(window.jQuery);
or declare variable $ after import
var $ = window.$
Although standard action results FileContentResult or FileStreamResult may be used for downloading files, for reusability, creating a custom action result might be the best solution.
As an example let's create a custom action result for exporting data to Excel files on the fly for download.
ExcelResult class inherits abstract ActionResult class and overrides the ExecuteResult method.
We are using FastMember package for creating DataTable from IEnumerable object and ClosedXML package for creating Excel file from the DataTable.
public class ExcelResult<T> : ActionResult
{
private DataTable dataTable;
private string fileName;
public ExcelResult(IEnumerable<T> data, string filename, string[] columns)
{
this.dataTable = new DataTable();
using (var reader = ObjectReader.Create(data, columns))
{
dataTable.Load(reader);
}
this.fileName = filename;
}
public override void ExecuteResult(ControllerContext context)
{
if (context != null)
{
var response = context.HttpContext.Response;
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("content-disposition", string.Format(@"attachment;filename=""{0}""", fileName));
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dataTable, "Sheet1");
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
response.BinaryWrite(stream.ToArray());
}
}
}
}
}
In the Controller use the custom ExcelResult action result as follows
[HttpGet]
public async Task<ExcelResult<MyViewModel>> ExportToExcel()
{
var model = new Models.MyDataModel();
var items = await model.GetItems();
string[] columns = new string[] { "Column1", "Column2", "Column3" };
string filename = "mydata.xlsx";
return new ExcelResult<MyViewModel>(items, filename, columns);
}
Since we are downloading the file using HttpGet, create an empty View without model and empty layout.
Blog post about custom action result for downloading files that are created on the fly:
https://acanozturk.blogspot.com/2019/03/custom-actionresult-for-files-in-aspnet.html
Normally you would select IDs using the ID selector #
, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):
div[id^="player_"]
If you are able to modify that HTML, however, you should add a class to your player div
s then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.
Try reinstall by using the below link,
Download https://bootstrap.pypa.io/get-pip.py
After download, copy the "get-pip.py" to python installed main dirctory, then open cmd and navigate to python directory and type "python get-pip.py" (without quotes)
Note: Also make sure the python directory is set in the environmental variable.
Hope this might help.
Open the created task scheduler
switch to the “Action” tab and select your created “Action”
In the Edit section, using the browser you could select powershell.exe in your system32\WindowsPowerShell\v1.0 folder.
Example -C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Next, in the ‘Add arguments’ -File parameter, paste your script file path in your system.
Example – c:\GetMFAStatus.ps1
This blog might help you to automate your Powershell scripts with windows task scheduler
Honestly, Wikipedia might be the best place to look for an answer to this.
If NP = P, then we can solve very hard problems much faster than we thought we could before. If we solve only one NP-Complete problem in P (polynomial) time, then it can be applied to all other problems in the NP-Complete category.
You can use System.Web.Script.Serialization.JavaScriptSerializer
:
Dictionary<string, object> dictss = new Dictionary<string, object>(){
{"User", "Mr.Joshua"},
{"Pass", "4324"},
};
string jsonString = (new JavaScriptSerializer()).Serialize((object)dictss);
Have a look at Styled Button it will surely help you. There are lots examples please search on INTERNET.
eg:style
<style name="Widget.Button" parent="android:Widget">
<item name="android:background">@drawable/red_dot</item>
</style>
you can use your selector instead of red_dot
red_dot:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#f00"/>
<size android:width="55dip"
android:height="55dip"/>
</shape>
Button:
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp"
style="@style/Widget.Button"
android:text="Button" />
This error also happens if you have got the order of your components wrong.
Example: this wrong:
<ComponentA>
<ComponentB>
</ComponentA>
</ComponentB>
correct way:
<ComponentA>
<ComponentB>
</ComponentB>
</ComponentA>
iWasRobbed's answer is great, except there is an AVCaptureSession running in the background all the time. On my iPhone 4s it takes about 12% CPU power according to Instrument so my app took about 1% battery in a minute. In other words if the device is prepared for AV capture it's not cheap.
Using the code below my app requires 0.187% a minute so the battery life is more than 5x longer.
This code works just fine on any device (tested on both 3GS (no flash) and 4s). Tested on 4.3 in simulator as well.
#import <AVFoundation/AVFoundation.h>
- (void) turnTorchOn:(BOOL)on {
Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
if (captureDeviceClass != nil) {
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if ([device hasTorch] && [device hasFlash]){
[device lockForConfiguration:nil];
if (on) {
[device setTorchMode:AVCaptureTorchModeOn];
[device setFlashMode:AVCaptureFlashModeOn];
torchIsOn = YES;
} else {
[device setTorchMode:AVCaptureTorchModeOff];
[device setFlashMode:AVCaptureFlashModeOff];
torchIsOn = NO;
}
[device unlockForConfiguration];
}
}
}
- hosts: lnx
tasks:
- find: paths="/appl/scripts/inq" recurse=yes patterns="inq.Linux*"
register: file_to_copy
- copy: src={{ item.path }} dest=/usr/local/sbin/
owner: root
mode: 0775
with_items: "{{ files_to_copy.files }}"
Using display:none is not SEO-friendly. The following way allows the hidden content to be searchable. Adding the transition-delay ensures any links included in the hidden content is clickable.
.collapse > p{
cursor: pointer;
display: block;
}
.collapse:focus{
outline: none;
}
.collapse > div {
height: 0;
width: 0;
overflow: hidden;
transition-delay: 0.3s;
}
.collapse:focus div{
display: block;
height: 100%;
width: 100%;
overflow: auto;
}
<div class="collapse" tabindex="1">
<p>Question 1</p>
<div>
<p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div>
<div class="collapse" tabindex="2">
<p>Question 2</p>
<div>
<p>Visit <a href="https://stackoverflow.com/">Stack Overflow</a></p>
</div>
</div>
It's Unicode.
Just put the variable between str()
, and it will work fine.
But in case you have two lists like the following:
a = ['co32','co36']
b = [u'co32',u'co36']
If you check set(a)==set(b)
, it will come as False, but if you do as follows:
b = str(b)
set(a)==set(b)
Now, the result will be True.
Voila!
div {_x000D_
background-color: red;_x000D_
color: white;_x000D_
font-weight: bold;_x000D_
width: 48px;_x000D_
height: 48px; _x000D_
transform: rotate(360deg);_x000D_
transition: transform 0.5s;_x000D_
}_x000D_
_x000D_
div:active {_x000D_
transform: rotate(0deg);_x000D_
transition: 0s;_x000D_
}
_x000D_
<div></div>
_x000D_
First we find the process id of that particular task which we need to eliminate in order to get the port free:
Type
netstat -n -a -o
After executing this command in the Windows command line prompt (cmd), select the pid which I think the last column. Suppose this is 3312.
Now type
taskkill /F /PID 3312
You can now cross check by typing the netstat
command.
NOTE: sometimes Windows doesn’t allow you to run this command directly on CMD, so first you need to go with these steps:
From the start menu -> command prompt (right click on command prompt, and run as administrator)
wc
can't get the filename if you don't give it one.
wc -l < "$JAVA_TAGS_FILE"
You need to handle it via ajax
submit.
Something like this:
$(function(){
$('#subscribe-email-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#subscribe-email-form').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
A better way would be to use a django form, and then render the following snippet:
<form>
<div class="modal-body">
<input type="email" placeholder="email"/>
<p>This service will notify you by email should any issue arise that affects your plivo service.</p>
</div>
<div class="modal-footer">
<input type="submit" value="SUBMIT" class="btn"/>
</div>
</form>
via the context - example : {{form}}
.
If You want to check only when scroll ended, in Vanilla JS, You can come up with a solution like this:
Super Super compact
var t
window.onresize = () => { clearTimeout(t) t = setTimeout(() => { resEnded() }, 500) }
function resEnded() { console.log('ended') }
All 3 possible combinations together (ES6)
var t
window.onresize = () => {
resizing(this, this.innerWidth, this.innerHeight) //1
if (typeof t == 'undefined') resStarted() //2
clearTimeout(t); t = setTimeout(() => { t = undefined; resEnded() }, 500) //3
}
function resizing(target, w, h) {
console.log(`Youre resizing: width ${w} height ${h}`)
}
function resStarted() {
console.log('Resize Started')
}
function resEnded() {
console.log('Resize Ended')
}
y <- mean(x, na.rm=TRUE)
sd(y)
for standard deviation var(y)
for variance.
Both derivations use n-1
in the denominator so they are based on sample data.
Don't. Leave them as Java and use IKVM to convert them to .Net DLLs.
def base(decimal ,base) :
list = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
other_base = ""
while decimal != 0 :
other_base = list[decimal % base] + other_base
decimal = decimal / base
if other_base == "":
other_base = "0"
return other_base
print base(31 ,16)
output:
"1F"
I created a fiddle using only CSS.
.wrapper {_x000D_
width: 100px; /* Set the size of the progress bar */_x000D_
height: 100px;_x000D_
position: absolute; /* Enable clipping */_x000D_
clip: rect(0px, 100px, 100px, 50px); /* Hide half of the progress bar */_x000D_
}_x000D_
/* Set the sizes of the elements that make up the progress bar */_x000D_
.circle {_x000D_
width: 80px;_x000D_
height: 80px;_x000D_
border: 10px solid green;_x000D_
border-radius: 50px;_x000D_
position: absolute;_x000D_
clip: rect(0px, 50px, 100px, 0px);_x000D_
}_x000D_
/* Using the data attributes for the animation selectors. */_x000D_
/* Base settings for all animated elements */_x000D_
div[data-anim~=base] {_x000D_
-webkit-animation-iteration-count: 1; /* Only run once */_x000D_
-webkit-animation-fill-mode: forwards; /* Hold the last keyframe */_x000D_
-webkit-animation-timing-function:linear; /* Linear animation */_x000D_
}_x000D_
_x000D_
.wrapper[data-anim~=wrapper] {_x000D_
-webkit-animation-duration: 0.01s; /* Complete keyframes asap */_x000D_
-webkit-animation-delay: 3s; /* Wait half of the animation */_x000D_
-webkit-animation-name: close-wrapper; /* Keyframes name */_x000D_
}_x000D_
_x000D_
.circle[data-anim~=left] {_x000D_
-webkit-animation-duration: 6s; /* Full animation time */_x000D_
-webkit-animation-name: left-spin;_x000D_
}_x000D_
_x000D_
.circle[data-anim~=right] {_x000D_
-webkit-animation-duration: 3s; /* Half animation time */_x000D_
-webkit-animation-name: right-spin;_x000D_
}_x000D_
/* Rotate the right side of the progress bar from 0 to 180 degrees */_x000D_
@-webkit-keyframes right-spin {_x000D_
from {_x000D_
-webkit-transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
-webkit-transform: rotate(180deg);_x000D_
}_x000D_
}_x000D_
/* Rotate the left side of the progress bar from 0 to 360 degrees */_x000D_
@-webkit-keyframes left-spin {_x000D_
from {_x000D_
-webkit-transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
-webkit-transform: rotate(360deg);_x000D_
}_x000D_
}_x000D_
/* Set the wrapper clip to auto, effectively removing the clip */_x000D_
@-webkit-keyframes close-wrapper {_x000D_
to {_x000D_
clip: rect(auto, auto, auto, auto);_x000D_
}_x000D_
}
_x000D_
<div class="wrapper" data-anim="base wrapper">_x000D_
<div class="circle" data-anim="base left"></div>_x000D_
<div class="circle" data-anim="base right"></div>_x000D_
</div>
_x000D_
Also check this fiddle here (CSS only)
@import url(http://fonts.googleapis.com/css?family=Josefin+Sans:100,300,400);_x000D_
_x000D_
.arc1 {_x000D_
width: 160px;_x000D_
height: 160px;_x000D_
background: #00a0db;_x000D_
-webkit-transform-origin: -31% 61%;_x000D_
margin-left: -30px;_x000D_
margin-top: 20px;_x000D_
-webkit-transform: translate(-54px,50px);_x000D_
-moz-transform: translate(-54px,50px);_x000D_
-o-transform: translate(-54px,50px);_x000D_
}_x000D_
.arc2 {_x000D_
width: 160px;_x000D_
height: 160px;_x000D_
background: #00a0db;_x000D_
-webkit-transform: skew(45deg,0deg);_x000D_
-moz-transform: skew(45deg,0deg);_x000D_
-o-transform: skew(45deg,0deg);_x000D_
margin-left: -180px;_x000D_
margin-top: -90px;_x000D_
position: absolute;_x000D_
-webkit-transition: all .5s linear;_x000D_
-moz-transition: all .5s linear;_x000D_
-o-transition: all .5s linear;_x000D_
}_x000D_
_x000D_
.arc-container:hover .arc2 {_x000D_
margin-left: -50px;_x000D_
-webkit-transform: skew(-20deg,0deg);_x000D_
-moz-transform: skew(-20deg,0deg);_x000D_
-o-transform: skew(-20deg,0deg);_x000D_
}_x000D_
_x000D_
.arc-wrapper {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border-radius:150px;_x000D_
background: #424242;_x000D_
overflow:hidden;_x000D_
left: 50px;_x000D_
top: 50px;_x000D_
position: absolute;_x000D_
}_x000D_
.arc-hider {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border-radius: 150px;_x000D_
border: 50px solid #e9e9e9;_x000D_
position:absolute;_x000D_
z-index:5;_x000D_
box-shadow:inset 0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
_x000D_
.arc-inset {_x000D_
font-family: "Josefin Sans";_x000D_
font-weight: 100;_x000D_
position: absolute;_x000D_
font-size: 413px;_x000D_
margin-top: -64px;_x000D_
z-index: 5;_x000D_
left: 30px;_x000D_
line-height: 327px;_x000D_
height: 280px;_x000D_
-webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0.2));_x000D_
}_x000D_
.arc-lowerInset {_x000D_
font-family: "Josefin Sans";_x000D_
font-weight: 100;_x000D_
position: absolute;_x000D_
font-size: 413px;_x000D_
margin-top: -64px;_x000D_
z-index: 5;_x000D_
left: 30px;_x000D_
line-height: 327px;_x000D_
height: 280px;_x000D_
color: white;_x000D_
-webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,0.2), rgba(0,0,0,1));_x000D_
}_x000D_
.arc-overlay {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-image: linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -o-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -moz-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -webkit-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
_x000D_
padding-left: 32px;_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
line-height: 100px;_x000D_
font-family: sans-serif;_x000D_
font-weight: 400;_x000D_
text-shadow: 0 1px 0 #fff;_x000D_
font-size: 22px;_x000D_
border-radius: 100px;_x000D_
position: absolute;_x000D_
z-index: 5;_x000D_
top: 75px;_x000D_
left: 75px;_x000D_
box-shadow:0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
.arc-container {_x000D_
position: relative;_x000D_
background: #e9e9e9;_x000D_
height: 250px;_x000D_
width: 250px;_x000D_
}
_x000D_
<div class="arc-container">_x000D_
<div class="arc-hider"></div>_x000D_
<div class="arc-inset">_x000D_
o_x000D_
</div>_x000D_
<div class="arc-lowerInset">_x000D_
o_x000D_
</div>_x000D_
<div class="arc-overlay">_x000D_
35%_x000D_
</div>_x000D_
<div class="arc-wrapper">_x000D_
<div class="arc2"></div>_x000D_
<div class="arc1"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Or this beautiful round progress bar with HTML5, CSS3 and JavaScript.
You could add another empty layout below that one and set them both to have the same layout weight. They should get 50% of the space each.
We had the same problem for accepting monetary values for Euro, since <input type="number" />
can't display Euro decimal and comma format.
We came up with a solution, to use <input type="number" />
for user input. After user types in the value, we format it and display as a Euro format by just switching to <input type="text" />
. This is a Javascript solution though, cuz you need a condition to decide between "user is typing" and "display to user" modes.
Here the link with Visuals to our solution: Input field type "Currency" problem solved
Hope this helps in some way!
I have posted this as a separate answer as it is unrelated to my existing answer.
This issue recently cropped up again for accessing a parent from an iframe referencing a subdomain and the existing fixes did not work.
This time the answer was to modify the document.domain of the parent page and the iframe to be the same. This will fool the same origin policy checks into thinking they co-exist on exactly the same domain (subdomains are considered a different host and fail the same origin policy check).
Insert the following to the <head>
of the page in the iframe to match the parent domain (adjust for your doctype).
<script>
document.domain = "mydomain.com";
</script>
Please note that this will throw an error on localhost development, so use a check like the following to avoid the error:
if (!window.location.href.match(/localhost/gi)) {
document.domain = "mydomain.com";
}
The main problem here is that it ignores all and any error: Out of memory, CPU is burning, user wants to stop, program wants to exit, Jabberwocky is killing users.
This is way too much. In your head, you're thinking "I want to ignore this network error". If something unexpected goes wrong, then your code silently continues and breaks in completely unpredictable ways that no one can debug.
That's why you should limit yourself to ignoring specifically only some errors and let the rest pass.
Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.
Java LinkedList provides both the addFirst(E e) and the push(E e) method that add an element to the front of the list.
https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#addFirst(E)
On both Operation Systems, must turnoff firewall. I using MS SERVER 2012 R2 & MS WIN-7 as a client. First of all call "RUN BOX" window logo button+ R, once RUN box appeared type "firewall.cpl" at Window Firewall setting you will see "Turn Window Firewall On or Off" like this you click it & chose "turn off window firewall" on both Private and Public Setting then OK. Ping again on guests OS. GOOD-LUCK Aungkokokhant
MySQL says:
All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.
When do I use it ?
Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED
data type.
A common mistake is to use a primary key that is an auto-increment INT
starting at zero, yet the type is SIGNED
, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.
With push you can even add multiple objects to an array
let myArray = [];
myArray.push(
{name:"James", dataType:TYPES.VarChar, Value: body.Name},
{name:"Boo", dataType:TYPES.VarChar, Value: body.Name},
{name:"Alina", dataType:TYPES.VarChar, Value: body.Name}
);
I've encountered such issue recently. Though code was correct, I didn't turn on permissions in app settings. So, all permissions hasn't been set by default on emulators, so you should do it yourself.
SWT was created as a response to the sluggishness of Swing around the turn of the century. Now that the differences in performance are becoming negligable, I think Swing is a better option for your standard applications. SWT/Eclipse has a nice framework which helps with a lot of boiler plate code.
For me the issue was SELinux enforcement rather than permissions. The "read only database" error went away once I disabled enforcement, following the suggestion made by Steve V. in a comment on the accepted answer.
echo 0 >/selinux/enforce
Upon running this command, everything worked as intended (CentOS 6.3).
The specific issue I had encountered was during setup of Graphite. I had triple-checked that the apache user owned and could write to both my graphite.db and its parent directory. But until I "fixed" SELinux, all I got was a stack trace to the effect of: DatabaseError: attempt to write a readonly database
There are many ways to scroll up and down in Selenium Webdriver I always use Java Script to do the same.
Below is the code which always works for me if I want to scroll up or down
// This will scroll page 400 pixel vertical
((JavascriptExecutor)driver).executeScript("scroll(0,400)");
You can get full code from here Scroll Page in Selenium
If you want to scroll for a element then below piece of code will work for you.
je.executeScript("arguments[0].scrollIntoView(true);",element);
You will get the full doc here Scroll for specific Element
Kotlin's way -
fun Context.bitMapFromImgUrl(imageUrl: String, callBack: (bitMap: Bitmap) -> Unit) {
GlideApp.with(this)
.asBitmap()
.load(imageUrl)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
callBack(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
// this is called when imageView is cleared on lifecycle call or for
// some other reason.
// if you are referencing the bitmap somewhere else too other than this imageView
// clear it here as you can no longer have the bitmap
}
})
}
I think that this is as easy as I can explain it. Please, anyone is welcome to correct me or add to this.
SOAP is a message format used by disconnected systems (like across the internet) to exchange information / data. It does with XML messages going back and forth.
Web services transmit or receive SOAP messages. They work differently depending on what language they are written in.
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
I use when I do a big commit, above all when I remove more files from the repository.. after, the commits are faster
Both the field name and the value should be url encoded. format of the post data and query string are the same
The .net way of doing is something like this
NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
outgoingQueryString.Add("field1","value1");
outgoingQueryString.Add("field2", "value2");
string postdata = outgoingQueryString.ToString();
This will take care of encoding the fields and the value names
This error occurs when you suspend some functions. Like running the query below with incorrect foreign key.
set foreign_key_checks=0
With a using of the hooks:
const useFade = () => {
const [ fade, setFade ] = useState(false);
const onMouseEnter = () => {
setFade(true);
};
const onMouseLeave = () => {
setFade(false);
};
const fadeStyle = !fade ? {
opacity: 1, transition: 'all .2s ease-in-out',
} : {
opacity: .5, transition: 'all .2s ease-in-out',
};
return { fadeStyle, onMouseEnter, onMouseLeave };
};
const ListItem = ({ style }) => {
const { fadeStyle, ...fadeProps } = useFade();
return (
<Paper
style={{...fadeStyle, ...style}}
{...fadeProps}
>
{...}
</Paper>
);
};
If you need the difference in days accounting up to the second:
SELECT TIMESTAMPDIFF(SECOND,'2010-09-21 21:40:36','2010-10-08 18:23:13')/86400 AS diff
It will return
diff
16.8629
About the most compact way to do this is:
Double array[] = { 1.0, 2.0, 3.0};
List<Double> list = Arrays.asList(array);
Use str.join
:
>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:
join(...)
S.join(iterable) -> str
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
>>>
There is a blog post on MSDN about why an exponent operator does NOT exists from the C# team.
It would be possible to add a power operator to the language, but performing this operation is a fairly rare thing to do in most programs, and it doesn't seem justified to add an operator when calling Math.Pow() is simple.
You asked:
Do I have to write a loop or include another namespace to handle exponential operations? If so, how do I handle exponential operations using non-integers?
Math.Pow
supports double parameters so there is no need for you to write your own.
It might be worth looking at a tutorial: MDN Canvas Tutorial
You can get the width and height of a canvas element simply by accessing those properties of the element. For example:
var canvas = document.getElementById('mycanvas');
var width = canvas.width;
var height = canvas.height;
If the width and height attributes are not present in the canvas element, the default 300x150 size will be returned. To dynamically get the correct width and height use the following code:
const canvasW = canvas.getBoundingClientRect().width;
const canvasH = canvas.getBoundingClientRect().height;
Or using the shorter object destructuring syntax:
const { width, height } = canvas.getBoundingClientRect();
The context
is an object you get from the canvas to allow you to draw into it. You can think of the context
as the API to the canvas, that provides you with the commands that enable you to draw on the canvas element.
If you need to load a file that's relative to some directory where you already are (like in the current directory), here's an easy solution:
File f;
if (System.getProperty("sun.arch.data.model").equals("32")) {
// 32-bit JVM
f = new File("mylibfile32.so");
} else {
// 64-bit JVM
f = new File("mylibfile64.so");
}
System.load(f.getAbsolutePath());
This should get the id added.
ASP.NET MVC 5 and lower:
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "signupform" }))
{ } %>
ASP.NET Core: You can use tag helpers in forms to avoid the odd syntax for setting the id.
<form asp-controller="Account" asp-action="Register" method="post" id="signupform" role="form"></form>
get
returns Collection
and is rather supposed to fetch multiple rows.
count
is a generic way of checking the result:
$user = User::where(...)->first(); // returns Model or null
if (count($user)) // do what you want with $user
// or use this:
$user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException
// count will works with a collection of course:
$users = User::where(...)->get(); // returns Collection always (might be empty)
if (count($users)) // do what you want with $users
Check out Android Documentation Managing Virtual Devices
Its boils down to this: math.h
is from C
and was created over 10 years ago. In math.h, due to its primitive nature, the abs()
function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs()
.
When C++ was created it took math.h
and made it cmath
. cmath
is essentially math.h but improved for C++. It improved things like having to distinguish between fabs()
and abs, and just made abs()
for both doubles and integer types.
In summary either:
Use math.h and use abs()
for integers, fabs()
for doubles
or
use cmath and just have abs for everything (easier and recommended)
Hope this helps anyone who is having the same problem!
JAX-RS implementations automatically support marshalling/unmarshalling of classes based on discoverable JAXB annotations, but because your payload is declared as Object
, I think the created JAXBContext
misses the Department
class and when it's time to marshall it it doesn't know how.
A quick and dirty fix would be to add a XmlSeeAlso
annotation to your response class:
@XmlRootElement
@XmlSeeAlso({Department.class})
public class Response implements Serializable {
....
or something a little more complicated would be "to enrich" the JAXB context for the Response
class by using a ContextResolver
:
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
@Provider
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public class ResponseResolver implements ContextResolver<JAXBContext> {
private JAXBContext ctx;
public ResponseResolver() {
try {
this.ctx = JAXBContext.newInstance(
Response.class,
Department.class
);
} catch (JAXBException ex) {
throw new RuntimeException(ex);
}
}
public JAXBContext getContext(Class<?> type) {
return (type.equals(Response.class) ? ctx : null);
}
}
In PHP, by default, objects are passed as reference to a new object.
See this example:
class X {
var $abc = 10;
}
class Y {
var $abc = 20;
function changeValue($obj)
{
$obj->abc = 30;
}
}
$x = new X();
$y = new Y();
echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 30
Now see this:
class X {
var $abc = 10;
}
class Y {
var $abc = 20;
function changeValue($obj)
{
$obj = new Y();
}
}
$x = new X();
$y = new Y();
echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 10 not 20 same as java does.
Now see this:
class X {
var $abc = 10;
}
class Y {
var $abc = 20;
function changeValue(&$obj)
{
$obj = new Y();
}
}
$x = new X();
$y = new Y();
echo $x->abc; //outputs 10
$y->changeValue($x);
echo $x->abc; //outputs 20 not possible in java.
I hope you can understand this.
I had the same problem when I ran my form application in Firefox. Adding <meta charset="utf-8"/>
in the html code solved my issue in Firefox.
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Voice clip upload</title>_x000D_
<script src="voiceclip.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h2>Upload Voice Clip</h2>_x000D_
<form id="upload_form" enctype="multipart/form-data" method="post">_x000D_
<input type="file" name="file1" id="file1" onchange="uploadFile()"><br>_x000D_
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>_x000D_
</form>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Check your short_open_tag setting (use <?php phpinfo() ?>
to see its current setting).
I had to do something similar to Sean and ilalex's answer.
But I had too many options to explicitly define the sort order for and only needed to float certain entries to the front of the list ... in the specified (non-natural) order.
Hopefully this is helpful to someone else.
public class CarComparator implements Comparator<Car> {
//sort these items in this order to the front of the list
private static List<String> ORDER = Arrays.asList("dd", "aa", "cc", "bb");
public int compare(final Car o1, final Car o2) {
int result = 0;
int o1Index = ORDER.indexOf(o1.getName());
int o2Index = ORDER.indexOf(o2.getName());
//if neither are found in the order list, then do natural sort
//if only one is found in the order list, float it above the other
//if both are found in the order list, then do the index compare
if (o1Index < 0 && o2Index < 0) result = o1.getName().compareTo(o2.getName());
else if (o1Index < 0) result = 1;
else if (o2Index < 0) result = -1;
else result = o1Index - o2Index;
return result;
}
//Testing output: dd,aa,aa,cc,bb,bb,bb,a,aaa,ac,ac,ba,bd,ca,cb,cb,cd,da,db,dc,zz
}
I find the answer here.
It's because the server variable local_infile
is set to FALSE|0. Refer from the document.
You can verify by executing:
SHOW VARIABLES LIKE 'local_infile';
If you have SUPER privilege you can enable it (without restarting server with a new configuration) by executing:
SET GLOBAL local_infile = 1;
You (as in the process that runs b.php
, either you through CLI
or a webserver) need write access to the directory in which the files are located. You are updating the directory content, so access to the file is not enough.
Note that if you use the PHP chmod()
function to set the mode of a file or folder to 777
you should use 0777
to make sure the number is correctly interpreted as an octal number.
Since image is deprecated, you should use varbinary.
per Microsoft (thanks for the link @Christopher)
ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.
Check out http://www.asciitable.com/
Look at the Hx
, (Hex) column; 2C
maps to ,
Any unusual encoding can be checked this way
+----+-----+----+-----+----+-----+----+-----+
| Hx | Chr | Hx | Chr | Hx | Chr | Hx | Chr |
+----+-----+----+-----+----+-----+----+-----+
| 00 | NUL | 20 | SPC | 40 | @ | 60 | ` |
| 01 | SOH | 21 | ! | 41 | A | 61 | a |
| 02 | STX | 22 | " | 42 | B | 62 | b |
| 03 | ETX | 23 | # | 43 | C | 63 | c |
| 04 | EOT | 24 | $ | 44 | D | 64 | d |
| 05 | ENQ | 25 | % | 45 | E | 65 | e |
| 06 | ACK | 26 | & | 46 | F | 66 | f |
| 07 | BEL | 27 | ' | 47 | G | 67 | g |
| 08 | BS | 28 | ( | 48 | H | 68 | h |
| 09 | TAB | 29 | ) | 49 | I | 69 | i |
| 0A | LF | 2A | * | 4A | J | 6A | j |
| 0B | VT | 2B | + | 4B | K | 6B | k |
| 0C | FF | 2C | , | 4C | L | 6C | l |
| 0D | CR | 2D | - | 4D | M | 6D | m |
| 0E | SO | 2E | . | 4E | N | 6E | n |
| 0F | SI | 2F | / | 4F | O | 6F | o |
| 10 | DLE | 30 | 0 | 50 | P | 70 | p |
| 11 | DC1 | 31 | 1 | 51 | Q | 71 | q |
| 12 | DC2 | 32 | 2 | 52 | R | 72 | r |
| 13 | DC3 | 33 | 3 | 53 | S | 73 | s |
| 14 | DC4 | 34 | 4 | 54 | T | 74 | t |
| 15 | NAK | 35 | 5 | 55 | U | 75 | u |
| 16 | SYN | 36 | 6 | 56 | V | 76 | v |
| 17 | ETB | 37 | 7 | 57 | W | 77 | w |
| 18 | CAN | 38 | 8 | 58 | X | 78 | x |
| 19 | EM | 39 | 9 | 59 | Y | 79 | y |
| 1A | SUB | 3A | : | 5A | Z | 7A | z |
| 1B | ESC | 3B | ; | 5B | [ | 7B | { |
| 1C | FS | 3C | < | 5C | \ | 7C | | |
| 1D | GS | 3D | = | 5D | ] | 7D | } |
| 1E | RS | 3E | > | 5E | ^ | 7E | ~ |
| 1F | US | 3F | ? | 5F | _ | 7F | DEL |
+----+-----+----+-----+----+-----+----+-----+
This should be understood in the context of GitHub forks (where you fork a GitHub repo on GitHub before cloning that fork locally).
upstream
generally refers to the original repo that you have forkeddownstream
” and “upstream
”" for more on upstream
term) origin
is your fork: your own repo on GitHub, clone of the original repo of GitHubFrom the GitHub page:
When a repo is cloned, it has a default remote called
origin
that points to your fork on GitHub, not the original repo it was forked from.
To keep track of the original repo, you need to add another remote namedupstream
git remote add upstream git://github.com/<aUser>/<aRepo.git>
(with aUser/aRepo
the reference for the original creator and repository, that you have forked)
You will use upstream
to fetch from the original repo (in order to keep your local copy in sync with the project you want to contribute to).
git fetch upstream
(git fetch
alone would fetch from origin
by default, which is not what is needed here)
You will use origin
to pull and push since you can contribute to your own repository.
git pull
git push
(again, without parameters, 'origin' is used by default)
You will contribute back to the upstream
repo by making a pull request.
I agree that Google's Gson
is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple
:
// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;
@Test
public void json2Object() {
// given
String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
+ "\"address\" : \"some address\","
+ "\"someobject\" : {\"field\" : \"value\"}}";
// when
JSONObject object = (JSONObject) JSONValue.parse(jsonString);
// then
@SuppressWarnings("unchecked")
Set<String> keySet = object.keySet();
for (String key : keySet) {
Object value = object.get(key);
System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
.getSimpleName());
}
assertThat(object.get("age").toString(), is("20"));
}
Pros and cons of Gson
and json-simple
is pretty much like pros and cons of user-defined Java Object and Map
. The object you define is clear for all fields (name and type), but less flexible than Map
.
Just use:
$output = array_merge($array1, $array2);
That should solve it. Because you use string keys if one key occurs more than one time (like '44'
in your example) one key will overwrite proceding ones with the same name. Because in your case they both have the same value anyway it doesn't matter and it will also remove duplicates.
Update: I just realised, that PHP treats the numeric string-keys as numbers (integers) and so will behave like this, what means, that it renumbers the keys too...
A workaround is to recreate the keys.
$output = array_combine($output, $output);
Update 2: I always forget, that there is also an operator (in bold, because this is really what you are looking for! :D)
$output = $array1 + $array2;
All of this can be seen in: http://php.net/manual/en/function.array-merge.php
A very simple check you can do with Cell formulas:
Sheet 1 (new - old)
=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")
Sheet 2 (old - new)
=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")
This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)
You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".
Doe the same for Sheet two.
Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.
But two cases are not covered here:
To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com
Traps and interrupts are closely related. Traps are a type of exception, and exceptions are similar to interrupts.
Intel x86 defines two overlapping categories, vectored events (interrupts vs exceptions), and exception classes (faults vs traps vs aborts).
All of the quotes in this post are from the April 2016 version of the Intel Software Developer Manual. For the (definitive and complex) x86 perspective, I recommend reading the SDM's chapter on Interrupt and Exception handling.
Vectored Events (interrupts and exceptions) cause the processor to jump into an interrupt handler after saving much of the processor's state (enough such that execution can continue from that point later).
Exceptions and interrupts have an ID, called a vector, that determines which interrupt handler the processor jumps to. Interrupt handlers are described within the Interrupt Descriptor Table.
Interrupts occur at random times during the execution of a program, in response to signals from hardware. System hardware uses interrupts to handle events external to the processor, such as requests to service peripheral devices. Software can also generate interrupts by executing the INT n instruction.
Exceptions occur when the processor detects an error condition while executing an instruction, such as division by zero. The processor detects a variety of error conditions including protection violations, page faults, and internal machine faults.
Exceptions are classified as faults, traps, or aborts depending on the way they are reported and whether the instruction that caused the exception can be restarted without loss of program or task continuity.
A trap is an exception that is reported immediately following the execution of the trapping instruction. Traps allow execution of a program or task to be continued without loss of program continuity. The return address for the trap handler points to the instruction to be executed after the trapping instruction.
A fault is an exception that can generally be corrected and that, once corrected, allows the program to be restarted with no loss of continuity. When a fault is reported, the processor restores the machine state to the state prior to the beginning of execution of the faulting instruction. The return address (saved contents of the CS and EIP registers) for the fault handler points to the faulting instruction, rather than to the instruction following the faulting instruction.
Example: A page fault is often recoverable. A piece of an application's address space may have been swapped out to disk from ram. The application will trigger a page fault when it tries to access memory that was swapped out. The kernel can pull that memory from disk to ram, and hand control back to the application. The application will continue where it left off (at the faulting instruction that was accessing swapped out memory), but this time the memory access should succeed without faulting.
An illegal-instruction fault handler that emulates floating-point or other missing instructions would have to manually increment the return address to get the trap-like behaviour it needs, after seeing if the faulting instruction was one it could handle. x86 #UD
is a "fault", not a "trap". (The handler would need a pointer to the faulting instruction to figure out which instruction it was.)
An abort is an exception that does not always report the precise location of the instruction causing the exception and does not allow a restart of the program or task that caused the exception. Aborts are used to report severe errors, such as hardware errors and inconsistent or illegal values in system tables.
Software invoked interrupts (triggered by the INT instruction) behave in a trap-like manner. The instruction completes before the processor saves its state and jumps to the interrupt handler.
You can run chrome with the --unsafely-treat-insecure-origin-as-secure="http://example.com" flag (replacing "example.com" with the origin you actually want to test), which will treat that origin as secure for this session. Note that you also need to include the --user-data-dir=/test/only/profile/dir to create a fresh testing profile for the flag to work.
For example if use Windows, Click Start and run.
chrome --unsafely-treat-insecure-origin-as-secure="http://localhost:8100" --user-data-dir=C:\testprofile
If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url
command:
git remote get-url origin
(nice pendant of git remote set-url origin <newurl>
)
See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf
).
(Merged by Junio C Hamano -- gitster
-- in commit e437cbd, 05 Oct 2015)
remote: add get-url subcommand
Expanding
insteadOf
is a part ofls-remote --url
and there is no way to expandpushInsteadOf
as well.
Add aget-url
subcommand to be able to query both as well as a way to get all configured urls.
The reason you get that is the order of precendence of the operators, and the fact that +
is used to both concatenate strings as well as perform numeric addition.
In your case, the concatenation of "question-" and i
is happening first giving the string "question=1". Then another string concatenation with "1" giving "question-11".
You just simply need to give the interpreter a hint as to what order of prec endence you want.
divID = "question-" + (i+1);
you can try
position: relative;
bottom: 20px;
but I don't see a problem on my browser (Google Chrome)
u should add a theme
to ur all activities (u should add theme
for all application in ur <application>
in ur manifest)
but if u have set different theme to ur activity u can use :
android:theme="@style/Theme.AppCompat"
or each kind of AppCompat
theme!
The challenge I see with the solution:
FROM(
SELECT top(100) *
FROM Customers
UNION
SELECT top(100) *
FROM CustomerEurope
UNION
SELECT top(100) *
FROM CustomerAsia
UNION
SELECT top(100) *
FROM CustomerAmericas
)
is that this creates a windowed data set that will reside in the RAM and on larger data sets this solution will create severe performance issues as it must first create the partition and then it will use the partition to write to the temp table.
A better solution would be the following:
SELECT top(100)* into #tmpFerdeen
FROM Customers
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerEurope
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAsia
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAmericas
to select insert into the temp table and then add additional rows. However the draw back here is if there are any duplicate rows in the data.
The Best Solution would be the following:
Insert into #tmpFerdeen
SELECT top(100)*
FROM Customers
UNION
SELECT top(100)*
FROM CustomerEurope
UNION
SELECT top(100)*
FROM CustomerAsia
UNION
SELECT top(100)*
FROM CustomerAmericas
This method should work for all purposes that require distinct rows. If, however, you want the duplicate rows simply swap out the UNION for UNION ALL
Best of luck!
I think your questions will all be answered if you understand how Sets, and in particular HashSets work. A set is a collection of unique objects, with Java defining uniqueness in that it doesn't equal anything else (equals returns false).
The HashSet takes advantage of hashcodes to speed things up. It assumes that two objects that equal eachother will have the same hash code. However it does not assume that two objects with the same hash code mean they are equal. This is why when it detects a colliding hash code, it only compares with other objects (in your case one) in the set with the same hash code.
Or, if you need to do something with each folder, have a look at the System.IO.DirectoryInfo class. It also has a Parent property that allows you to navigate to the parent directory.
In my case (referencing a PHP file in the top folder of a Wordpress plugin) I had to change the permissions on that folder. My test environment was fine, but when deployed the folder had 775. I changed it to 755 and it works fine.
This is an old post, but I thought I would add another method to do this:
var win = window.open("http://www.google.com");
var winClosed = setInterval(function () {
if (win.closed) {
clearInterval(winClosed);
foo(); //Call your function here
}
}, 250);
You don't have to modify the contents or use any event handlers from the child window.
Giving an element the attribute readonly
will give that element the readonly status. It doesn't matter what value you put after it or if you put any value after it, it will still see it as readonly. Putting readonly="false"
won't work.
Suggested is to use the W3C standard, which is readonly="readonly"
.
Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do
$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java
To run do
$java -cp .:a.jar:b.jar:c.jar HelloWorld
If you've included the file correctly and file exists and still getting error:
Then make sure:
Your included file contains the class and is not defined within any namespace.
If the class is in a namespace then:
instead of new YourClass()
you've to do new YourNamespace\YourClass()