WebSockets is definitely the future.
Long polling is a dirty workaround to prevent creating connections for each request like AJAX does -- but long polling was created when WebSockets didn't exist. Now due to WebSockets, long polling is going away.
WebRTC allows for peer-to-peer communication.
I recommend learning WebSockets.
of different communication techniques on the web
AJAX - request
→ response
. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection.
Supported in all major browsers.
Long poll - request
→ wait
→ response
. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic.
support chart (full) | wikipedia
WebSockets - client
↔ server
. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted.
support chart (very good) | wikipedia
WebRTC - peer
↔ peer
. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to "link" peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required.
support chart (medium) | wikipedia
Server-Sent Events - client
← server
. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE) | wikipedia
The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don't need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.
People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it's connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).
Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.
You should use the fuser command.
Eg. fuser /dev/cdrom
will return the pid(s) of the process using /dev/cdrom
.
If you are trying to unmount, you can kill theses process using the -k
switch (see man fuser
).
You can use native win command:
WMIC /node:ComputerName process call create “cmd.exe /c start.exe”
The WMIC is part of wbem win folder: C:\Windows\System32\wbem
The change
event is limited to input
, textarea
& and select
.
See http://api.jquery.com/change/ for more information.
Following event handler should do the needful:
$('[name=mobilePhone]').on('keyup', function(e){
var enteredNumberStr=this.$('[name=mobilePhone]').val(),
//Filter only numbers from the input
cleanedStr = (enteredNumberStr).replace(/\D/g, ''),
inputLength=cleanedStr.length,
formattedNumber=cleanedStr;
if(inputLength>3 && inputLength<7) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,inputLength-1) ;
}else if (inputLength>=7 && inputLength<10) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);
}else if(inputLength>=10) {
formattedNumber= cleanedStr.substr(0,3) + '-' + cleanedStr.substr(3,3) + '-' + cleanedStr.substr(6,inputLength-1);
}
console.log(formattedNumber);
this.$('[name=mobilePhone]').val(formattedNumber);
});
A full example with Zebra_Image library, that I think is so easy and useful. There are a lot of code, but if you read it, there are a lot of comments too so you can make copy and paste to use it quickly.
This example validates image format, size and replace image size with custom resolution. There is Zebra library and documentation (download only Zebra_Image.php file).
Explanation:
Main function
private function uploadImage() {
$target_file = "../img/blog/";
//this function could be in the same PHP file or class. I use a Helper (see bellow)
if(UsersUtils::uploadFile($target_file, $this->selectedBlog->getId())) {
//This function is at same Helper class.
//The image will be returned allways if there isn't errors uploading it, for this reason there aren't validations here.
$blogPhotoPath = UsersUtils::getUserFile($target_file, $this->selectedBlog->getId());
// create a new instance of the class
$imageHelper = new Zebra_Image();
// indicate a source image
$imageHelper->source_path = $blogPhotoPath;
// indicate a target image
$imageHelper->target_path = $blogPhotoPath;
// since in this example we're going to have a jpeg file, let's set the output
// image's quality
$imageHelper->jpeg_quality = 100;
// some additional properties that can be set
// read about them in the documentation
$imageHelper->preserve_aspect_ratio = true;
$imageHelper->enlarge_smaller_images = true;
$imageHelper->preserve_time = true;
$imageHelper->handle_exif_orientation_tag = true;
// resize
// and if there is an error, show the error message
if (!$imageHelper->resize(450, 310, ZEBRA_IMAGE_CROP_CENTER)) {
// if there was an error, let's see what the error is about
switch ($imageHelper->error) {
case 1:
echo 'Source file could not be found!';
break;
case 2:
echo 'Source file is not readable!';
break;
case 3:
echo 'Could not write target file!';
break;
case 4:
echo 'Unsupported source file format!';
break;
case 5:
echo 'Unsupported target file format!';
break;
case 6:
echo 'GD library version does not support target file format!';
break;
case 7:
echo 'GD library is not installed!';
break;
case 8:
echo '"chmod" command is disabled via configuration!';
break;
case 9:
echo '"exif_read_data" function is not available';
break;
}
} else {
echo 'Image uploaded with new size without erros');
}
}
}
External functions or use at same PHP file removing public static qualifiers.
public static function uploadFile($targetDir, $fileName) {
// File upload path
$fileUploaded = $_FILES["input-file"];
$fileType = pathinfo(basename($fileUploaded["name"]),PATHINFO_EXTENSION);
$targetFilePath = $targetDir . $fileName .'.'.$fileType;
if(empty($fileName)){
echo 'Error: any file found inside this path';
return false;
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(in_array($fileType, $allowTypes)){
//Max buffer length 8M
var_dump(ob_get_length());
if(ob_get_length() > 8388608) {
echo 'Error: Max size available 8MB';
return false;
}
// Upload file to server
if(move_uploaded_file($fileUploaded["tmp_name"], $targetFilePath)){
return true;
}else{
echo 'Error: error_uploading_image.';
}
}else{
echo 'Error: Only files JPG, JPEG, PNG, GIF y PDF types are allowed';
}
return false;
}
public static function getUserFile($targetDir, $userId) {
$userImages = glob($targetDir.$userId.'.*');
return !empty($userImages) ? $userImages[0] : null;
}
i would recommend going to http://sourceforge.net/projects/py2exe/files/latest/download?source=files to download py2exe. Then make a python file named setup.py. Inside it, type
from distutils.core import setup
import py2exe
setup(console=['nameoffile.py'])
Save in your user folder Also save the file you want converted in that same folder
Run window's command prompt
type in setup.py install py2exe
It should print many lines of code...
Next, open the dist folder.
Run the exe
file.
If there are needed files for the program to work, move them to the folder
Copy/Send the dist folder to person.
Optional: Change the name of the dist folder
Hope it works!:)
I encountered the same error. My linker command did have the rt library included -lrt
which is correct and it was working for a while. After re-installing Kubuntu it stopped working.
A separate forum thread suggested the -lrt
needed to come after the project object files.
Moving the -lrt
to the end of the command fixed this problem for me although I don't know the details of why.
If you created your provisioning profile before configuring the app ID
for push, try to regenerate the provisioning profile.
iOS Provisioning Portal -> Provisioning -> Your cert -> EDIT -> Make an edit -> Download new provisioning
Worked for me. Now i'm able to use push.
I have this:
def has_extension(filename, extension):
ext = "." + extension
if filename.endswith(ext):
return True
else:
return False
This did the job (in the year 2012):
#include <stdio.h>
const unsigned long long size = 8ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
FILE* pFile;
pFile = fopen("file.binary", "wb");
for (unsigned long long j = 0; j < 1024; ++j){
//Some calculations to fill a[]
fwrite(a, 1, size*sizeof(unsigned long long), pFile);
}
fclose(pFile);
return 0;
}
I just timed 8GB in 36sec, which is about 220MB/s and I think that maxes out my SSD. Also worth to note, the code in the question used one core 100%, whereas this code only uses 2-5%.
Thanks a lot to everyone.
Update: 5 years have passed it's 2017 now. Compilers, hardware, libraries and my requirements have changed. That's why I made some changes to the code and did some new measurements.
First up the code:
#include <fstream>
#include <chrono>
#include <vector>
#include <cstdint>
#include <numeric>
#include <random>
#include <algorithm>
#include <iostream>
#include <cassert>
std::vector<uint64_t> GenerateData(std::size_t bytes)
{
assert(bytes % sizeof(uint64_t) == 0);
std::vector<uint64_t> data(bytes / sizeof(uint64_t));
std::iota(data.begin(), data.end(), 0);
std::shuffle(data.begin(), data.end(), std::mt19937{ std::random_device{}() });
return data;
}
long long option_1(std::size_t bytes)
{
std::vector<uint64_t> data = GenerateData(bytes);
auto startTime = std::chrono::high_resolution_clock::now();
auto myfile = std::fstream("file.binary", std::ios::out | std::ios::binary);
myfile.write((char*)&data[0], bytes);
myfile.close();
auto endTime = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}
long long option_2(std::size_t bytes)
{
std::vector<uint64_t> data = GenerateData(bytes);
auto startTime = std::chrono::high_resolution_clock::now();
FILE* file = fopen("file.binary", "wb");
fwrite(&data[0], 1, bytes, file);
fclose(file);
auto endTime = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}
long long option_3(std::size_t bytes)
{
std::vector<uint64_t> data = GenerateData(bytes);
std::ios_base::sync_with_stdio(false);
auto startTime = std::chrono::high_resolution_clock::now();
auto myfile = std::fstream("file.binary", std::ios::out | std::ios::binary);
myfile.write((char*)&data[0], bytes);
myfile.close();
auto endTime = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}
int main()
{
const std::size_t kB = 1024;
const std::size_t MB = 1024 * kB;
const std::size_t GB = 1024 * MB;
for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option1, " << size / MB << "MB: " << option_1(size) << "ms" << std::endl;
for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option2, " << size / MB << "MB: " << option_2(size) << "ms" << std::endl;
for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option3, " << size / MB << "MB: " << option_3(size) << "ms" << std::endl;
return 0;
}
This code compiles with Visual Studio 2017 and g++ 7.2.0 (a new requirements). I ran the code with two setups:
Which gave the following measurements (after ditching the values for 1MB, because they were obvious outliers): Both times option1 and option3 max out my SSD. I didn't expect this to see, because option2 used to be the fastest code on my old machine back then.
TL;DR: My measurements indicate to use std::fstream
over FILE
.
A class based clean to use solution:
import signal
import time
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
self.kill_now = True
if __name__ == '__main__':
killer = GracefulKiller()
while not killer.kill_now:
time.sleep(1)
print("doing something in a loop ...")
print("End of the program. I was killed gracefully :)")
When I had similar problem gem update --system
helped me. Run this before bundle install
private int[] data = new int[3];
This already initializes your array elements to 0. You don't need to repeat that again in the constructor.
In your constructor it should be:
data = new int[]{0, 0, 0};
While setting the paste mode with paste/nopaste/pastetoggle
is perfectly fine, you still have to manually enable paste mode before pasting and disable paste mode after pasting. Being the lazy person that I am, below is the best solution that I've found so far, which automatically toggles the paste mode when you paste.
Here's a little trick that uses terminal's bracketed paste mode to automatically set/unset Vim's paste mode when you paste. Put following in your .vimrc:
let &t_SI .= "\<Esc>[?2004h" let &t_EI .= "\<Esc>[?2004l" inoremap <special> <expr> <Esc>[200~ XTermPasteBegin() function! XTermPasteBegin() set pastetoggle=<Esc>[201~ set paste return "" endfunction
Now you can paste without explicitly turning paste mode on/off - it is handled automatically for you.
Source: Coderwall
Note: This solution doesn't work in WSL (Windows 10 Subsystem for Linux). If anyone has a solution for WSL, please update this answer or add it in the comments.
Tmux If using tmux, then the declarations need to be double escaped. The code for this is also in Coderwall
if your table is like this
rowId col1 col2 col3 col4
1 a e 12 2
2 b f 42 5
3 a e 32 2
4 b f 44 5
var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 = r.Field<int>("col1"), pp2 = r.Field<int>("col2")});
To show action items (action buttons) in the ActionBar of fragments where they are only needed, do this:
Lets say you want the save
button to only show in the fragment where you accept input for items and not in the Fragment where you view a list of items, add this to the OnCreateOptionsMenu
method of the Fragment where you view the items:
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (menu != null) {
menu.findItem(R.id.action_save_item).setVisible(false);
}
}
NOTE: For this to work, you need the onCreate()
method in your Fragment (where you want to hide item button, the item view fragment in our example) and add setHasOptionsMenu(true)
like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
Might not be the best option, but it works and it's simple.
I made a solution based in part by the information above. I just set the titleLabel.text to the string I want to pass, and set the titleLabel.hidden = YES
Like this :
UIButton *imageclick = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
imageclick.frame = photoframe;
imageclick.titleLabel.text = [NSString stringWithFormat:@"%@.%@", ti.mediaImage, ti.mediaExtension];
imageclick.titleLabel.hidden = YES;
This way, there is no need for a inheritance or category and there is no memory leak
Note: SYSDATE - returns only date, i.e., "yyyy-mm-dd" is not correct. SYSDATE returns the system date of the database server including hours, minutes, and seconds. For example:
SELECT SYSDATE FROM DUAL; will return output similar to the following: 12/15/2017 12:42:39 PM
In RatingBar
give attribute:
style="?android:attr/ratingBarStyleIndicator"
Try CSS:
<h2 style="color:#069">Process Report</h2>
If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:
<style type="text/css">
h2 {
color:#069;
}
</style>
A good resource start off point would be MSDN as your looking into a microsoft product
I had similar issues. I work on a Windows tool chain with a shared repository with Linux guys, and they happily create files with the same (except for case) names in a given folder.
The effect is that I can clone the repository and immediately have dozens of 'modified' files that, if I checked in, would create havoc.
I have Windows set to case sensitive and Git to not ignore case, but it still fails (in the Win32 API calls apparently).
If I gitignore the files then I have to remember to not track the .gitignore file.
But I found a good answer here:
http://archive.robwilkerson.org/2010/03/02/git-tip-ignore-changes-to-tracked-files/index.html
this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.
Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output
As chars
can be represented as Integers (ASCII-Codes), you can simply write:
char c = 0;
The 0 in ASCII-Code is null
.
Adding to ben.bourdin answer, you can at least in any HTML based application, check if the browser supports HLS in its video element:
Let´s assume that your video element ID is "myVideo", then through javascript you can use the "canPlayType" function (http://www.w3schools.com/tags/av_met_canplaytype.asp)
var videoElement = document.getElementById("myVideo");
if(videoElement.canPlayType('application/vnd.apple.mpegurl') === "probably" || videoElement.canPlayType('application/vnd.apple.mpegurl') === "maybe"){
//Actions like playing the .m3u8 content
}
else{
//Actions like playing another video type
}
The canPlayType function, returns:
"" when there is no support for the specified audio/video type
"maybe" when the browser might support the specified audio/video type
"probably" when it most likely supports the specified audio/video type (you can use just this value in the validation to be more sure that your browser supports the specified type)
Hope this help :)
Best regards!
A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.
This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.
Whereas a GridLayout is a layout that places its children in a rectangular grid.
It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.
PHP-FPM is a service that spawns new PHP processes when needed, usually through a fast-cgi module like nginx. You can tell (with a margin of error) by just checking the init.d script e.g. "sudo /etc/init.d/php-fpm status"
What port or unix file socket is being used is up to the configuration, but often is just TCP port 9000. i.e. 127.0.0.1:9000
The best way to tell if it is running correctly is to have nginx running, and setup a virtual host that will fast-cgi pass to PHP-FPM, and just check it with wget or a browser.
What is the difference?
From the documentation:
- - (Boolean)
instance_of?(class)
- Returns
true
ifobj
is an instance of the given class.
and:
- - (Boolean)
is_a?(class)
- (Boolean)kind_of?(class)
- Returns
true
ifclass
is the class ofobj
, or ifclass
is one of the superclasses ofobj
or modules included inobj
.
If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.
When should I use which?
Never. Use polymorphism instead.
Why are there so many of them?
I wouldn't call two "many". There are two of them, because they do two different things.
To exit from Python terminal, simply just do:
exit()
Please pay attention it's a function which called as most user mix it with exit without calling, but new Pyhton terminal show a message...
or as a shortcut, press:
Ctrl + D
on your keyboard...
command prompt:
C:\Users\admin>java -version (Press Enter>
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)
Shamelessly copied from Generic deserialization of an xml string
public static T DeserializeFromXmlString<T>(string xmlString)
{
var serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(xmlString))
{
return (T) serializer.Deserialize(reader);
}
}
The difference lies in whether mixing colours results in LIGHTER or DARKER colours. When mixing light, the result is a lighter colour, so mixing red light and blue light becomes a lighter pink. When mixing paint (or ink), red and blue become a darker purple. Mixing paint results in DARKER colours, whereas mixing light results in LIGHTER colours. Therefore for paint the primary colours are Red Yellow Blue (or Cyan Magenta Yellow) as you stated. Yet for light the primary colours are Red Green Blue. It is (virtually) impossible to mix Red Green Blue paint into Yellow paint, or mixing Red Yellow Blue light into Green light.
My use case is similar, except that I want a log cleanup event to run at 2am every night. As I said in the comment above, the DAY_HOUR doesn't work for me. In my case I don't really mind potentially missing the first day (and, given it is to run at 2am then 2am tomorrow is almost always the next 2am) so I use:
CREATE EVENT applog_clean_event
ON SCHEDULE
EVERY 1 DAY
STARTS str_to_date( date_format(now(), '%Y%m%d 0200'), '%Y%m%d %H%i' ) + INTERVAL 1 DAY
COMMENT 'Test'
DO
I am updating @Aliceljm answer here. Since the decimal place matters for 1,2 digit numbers, I am round off the first decimal place and keep the first decimal place. For 3 digit number, I am round off the units place and ignoring the all decimal places.
getMultiplers : function(bytes){
var unit = 1000 ;
if (bytes < unit) return bytes ;
var exp = Math.floor(Math.log(bytes) / Math.log(unit));
var pre = "kMGTPE".charAt(exp-1);
var result = bytes / Math.pow(unit, exp);
if(result/100 < 1)
return (Math.round( result * 10 ) / 10) +pre;
else
return Math.round(result) + pre;
}
look at this: https://developer.mozilla.org/en-US/docs/Web/API/event.keyCode
In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g. 'a'), charCode is set to the code of that character, respecting the letter case. (i.e. charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode. keyCode is always set in the keydown and keyup events. In these cases, charCode is never set. To get the code of the key regardless of whether it was stored in keyCode or charCode, query the which property. Characters entered through an IME do not register through keyCode or charCode.
Also remember that it must be:
#include "stdafx.h"
#include <iostream>
and not the other way around
#include <iostream>
#include "stdafx.h"
from jQuery v1.6 use prop
to check that is checkd or not
$('input:radio').prop('checked') // will return true or false
and to make it checkd use
$("input").prop("checked", true);
The folder mapping can be found in .git/modules
folder (each has config
file with reference to its worktree
), so make sure these folders correspond to the configuration in .gitmodules
and .git/config
.
So .gitmodules
has the correct path:
[submodule "<path>"]
path = <path>
url = [email protected]:foo/bar.git
and in .git/modules/<path>/config
in [core]
section you've the right path to your <path>
, e.g.
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
worktree = ../../../<path>
If the right folder in .git/modules
is missing, then you've to go to your submodule dir and try git reset HEAD --hard
or git checkout master -f
. If this won't help, you probably want to remove all the references to the broken submodule and add it again, then see: Rename a git submodule.
Use the -H
header again before the Authorization:Basic things. So it will be
curl -i \
-H 'Accept:application/json' \
-H 'Authorization:Basic BASE64_string' \
http://example.com
Here, BASE64_string
= Base64 of username:password
MS's query explaining the use of the KILL
command is quite useful providing connection's information:
SELECT conn.session_id, host_name, program_name,
nt_domain, login_name, connect_time, last_request_end_time
FROM sys.dm_exec_sessions AS sess
JOIN sys.dm_exec_connections AS conn
ON sess.session_id = conn.session_id;
Another late answer... Here's how Microsoft uses it in their wchar.h
. Notice they also disable Warning C6386:
__inline _CRT_INSECURE_DEPRECATE_MEMORY(wmemcpy_s) wchar_t * __CRTDECL
wmemcpy(_Out_opt_cap_(_N) wchar_t *_S1, _In_opt_count_(_N) const wchar_t *_S2, _In_ size_t _N)
{
#pragma warning( push )
#pragma warning( disable : 4996 6386 )
return (wchar_t *)memcpy(_S1, _S2, _N*sizeof(wchar_t));
#pragma warning( pop )
}
There is a really cool solution from Danny Markov for that. It uses navigator.getUserMedia method and should work in modern browsers. I have tested it successfully with Firefox and Chrome. IE didn't work:
Here is a demo:
https://tutorialzine.github.io/pwa-photobooth/
Link to Danny Markovs description page:
http://tutorialzine.com/2016/09/everything-you-should-know-about-progressive-web-apps/
Link to GitHub:
I had a very similiar problem as I was not able to connect to TFS with my own credentials. Turned out that the user who had created the image (I was using Hyper-V) stored his account in Credential Manager. There was no way to change this in Visual Studio. To solve the issue, I opened Credential Manager in Control Panel and edited the Generic Credentials to be my own account. I closed and opened Visual Studio 2012, and reconnected to TFS. It prompted me for my credentials, but it connected with my account from then on.
hope this helps, sivilian
Let's understand renaming by a small example...
Renaming columns using mapping:
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) # Creating a df with column name A and B
df.rename({"A": "new_a", "B": "new_b"}, axis='columns', inplace =True) # Renaming column A with 'new_a' and B with 'new_b'
Output:
new_a new_b
0 1 4
1 2 5
2 3 6
Renaming index/Row_Name using mapping:
df.rename({0: "x", 1: "y", 2: "z"}, axis='index', inplace =True) # Row name are getting replaced by 'x', 'y', and 'z'.
Output:
new_a new_b
x 1 4
y 2 5
z 3 6
If you need to order your code into namespaces, just use the keyword namespace
:
file1.php
namespace foo\bar;
In file2.php
$obj = new \foo\bar\myObj();
You can also use use
. If in file2 you put
use foo\bar as mypath;
you need to use mypath
instead of bar
anywhere in the file:
$obj = new mypath\myObj();
Using use foo\bar;
is equal to use foo\bar as bar;
.
If you just want to print a double
with two digits after the decimal point, use something like this:
double value = 200.3456;
System.out.printf("Value: %.2f", value);
If you want to have the result in a String
instead of being printed to the console, use String.format()
with the same arguments:
String result = String.format("%.2f", value);
Or use class DecimalFormat
:
DecimalFormat df = new DecimalFormat("####0.00");
System.out.println("Value: " + df.format(value));
ALTER TABLE users
DROP CONSTRAINT 'constraints_name'
You already have the right answer. And if you want to make more complicated and interesting operations between Lists (collections) use apache commons collections (CollectionUtils) It allows you to make conjuction/disjunction, find intersection, check if one collection is a subset of another and other nice things.
In Oracle, there is two views that describe columns:
DBA_TAB_COLUMNS describes the columns of all tables, views, and clusters in the database.
USER_TAB_COLUMNS describes the columns of the tables, views, and
clusters owned by the current user. This view does not display the
OWNER column.
I came across this post while trying to figure out how to get OrderedDict to work. PyDev for Eclipse couldn't find OrderedDict at all, so I ended up deciding to make a tuple of my dictionary's key values as I would like them to be ordered. When I needed to output my list, I just iterated through the tuple's values and plugged the iterated 'key' from the tuple into the dictionary to retrieve my values in the order I needed them.
example:
test_dict = dict( val1 = "hi", val2 = "bye", val3 = "huh?", val4 = "what....")
test_tuple = ( 'val1', 'val2', 'val3', 'val4')
for key in test_tuple: print(test_dict[key])
It's a tad cumbersome, but I'm pressed for time and it's the workaround I came up with.
note: the list of lists approach that somebody else suggested does not really make sense to me, because lists are ordered and indexed (and are also a different structure than dictionaries).
01. Open the page for which you want to get the information.
02. Clear the address bar [where you type the address of the sites]:
and type or copy/paste from below:
javascript:alert(document.lastModified)
03. Press Enter or Go button.
Here's a list of the environment variables. I think you might want CURRENT_VARIANT
. See also BUILD_VARIANTS
.
This is now part of the language. See TypeScriptLang.org > Basic Types > enum for the documentation on this. An excerpt from the documentation on how to use these enums:
enum Color {Red, Green, Blue};
var c: Color = Color.Green;
Or with manual backing numbers:
enum Color {Red = 1, Green = 2, Blue = 4};
var c: Color = Color.Green;
You can also go back to the enum name by using for example Color[2]
.
Here's an example of how this all goes together:
module myModule {
export enum Color {Red, Green, Blue};
export class MyClass {
myColor: Color;
constructor() {
console.log(this.myColor);
this.myColor = Color.Blue;
console.log(this.myColor);
console.log(Color[this.myColor]);
}
}
}
var foo = new myModule.MyClass();
This will log:
undefined 2 Blue
Because, at the time of writing this, the Typescript Playground will generate this code:
var myModule;
(function (myModule) {
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(myModule.Color || (myModule.Color = {}));
var Color = myModule.Color;
;
var MyClass = (function () {
function MyClass() {
console.log(this.myColor);
this.myColor = Color.Blue;
console.log(this.myColor);
console.log(Color[this.myColor]);
}
return MyClass;
})();
myModule.MyClass = MyClass;
})(myModule || (myModule = {}));
var foo = new myModule.MyClass();
This is what I do on debian - I suspect it should work on ubuntu (amend the version as required + adapt the folder where you want to copy the JDK files as you wish, I'm using /opt/jdk
):
wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u71-b15/jdk-8u71-linux-x64.tar.gz
sudo mkdir /opt/jdk
sudo tar -zxf jdk-8u71-linux-x64.tar.gz -C /opt/jdk/
rm jdk-8u71-linux-x64.tar.gz
Then update-alternatives:
sudo update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_71/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /opt/jdk/jdk1.8.0_71/bin/javac 1
Select the number corresponding to the /opt/jdk/jdk1.8.0_71/bin/java
when running the following commands:
sudo update-alternatives --config java
sudo update-alternatives --config javac
Finally, verify that the correct version is selected:
java -version
javac -version
I want to post a simple solution for every schema you've got. If you are using MySQL DB, you can simply get from your schema all the table's name and add the WHERE-LIKE condition on it. You also could do it with the usual command line as follows:
SHOW TABLES WHERE tables_in_<your_shcema_name> LIKE '%<table_partial_name>%';
where tables_in_<your_shcema_name>
returns the column's name of SHOW TABLES
command.
One important thing I missed from the tutorials for a while (stolen from http://www.tramontana.co.hu/wix/lesson4.php) which resulted in the "Another version of this product is already installed" errors:
*Small updates mean small changes to one or a few files where the change doesn't warrant changing the product version (major.minor.build). You don't have to change the Product GUID, either. Note that you always have to change the Package GUID when you create a new .msi file that is different from the previous ones in any respect. The Installer keeps track of your installed programs and finds them when the user wants to change or remove the installation using these GUIDs. Using the same GUID for different packages will confuse the Installer.
Minor upgrades denote changes where the product version will already change. Modify the Version attribute of the Product tag. The product will remain the same, so you don't need to change the Product GUID but, of course, get a new Package GUID.
Major upgrades denote significant changes like going from one full version to another. Change everything: Version attribute, Product and Package GUIDs.
Download Google apps (GoogleLoginService.apk , GoogleServicesFramework.apk , Phonesky.apk)
from here.
Start your emulator:
emulator -avd VM_NAME_HERE -partition-size 500 -no-audio -no-boot-anim
Then use the following commands:
# Remount in rw mode.
# NOTE: more recent system.img files are ext4, not yaffs2
adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system
# Allow writing to app directory on system partition
adb shell chmod 777 /system/app
# Install following apk
adb push GoogleLoginService.apk /system/app/.
adb push GoogleServicesFramework.apk /system/app/.
adb push Phonesky.apk /system/app/. # Vending.apk in older versions
adb shell rm /system/app/SdkSetup*
var word = document.getElementById("word").value;//by id
or
var word = document.forms[0].elements[0].value;//by index
//word = a word from form input
var kodlandi = escape(word);//apply url encoding
alert(escape(word));
or
alert(kodlandi);
the problem you are not using encoding for input values from form so not browser adds ones to ...
ontop has some problems as unicode encoding/decoding operations so use this function encoding strings/arrays
function urlencode( str )
{
// http://kevin.vanzonneveld.net3.
// + original by: Philip Peterson4.
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)5.
// * example 1: urlencode('Kevin van Zonneveld!');
// * returns 1: 'Kevin+van+Zonneveld%21'7.
var ret = str;
ret = ret.toString();
ret = encodeURIComponent(ret);
ret = ret.replace(/%20/g, '+');
return ret;
}
ex.
var word = "some word";
word = urlencode(word);
You can also get through it by the code below:
file=open(completefilepath,'r',encoding='utf8',errors="ignore")
file.read()
To customize markers, you can do it from this online tool: https://materialdesignicons.com/
In your case, you want the map-marker which is available here: https://materialdesignicons.com/icon/map-marker and which you can customize online.
If you simply want to change the default Red color to Blue, you can load this icon: http://maps.google.com/mapfiles/ms/icons/blue-dot.png
It's been mentioned in this thread: https://stackoverflow.com/a/32651327/6381715
I know this is an old thread... but as many people are searching for ways to undo stuff in Git, I still think it may be a good idea to continue giving tips here.
When you do a "git add" or move anything from the top left to the bottom left in git gui the content of the file is stored in a blob and the file content is possible to recover from that blob.
So it is possible to recover a file even if it was not committed but it has to have been added.
git init
echo hello >> test.txt
git add test.txt
Now the blob is created but it is referenced by the index so it will no be listed with git fsck until we reset. So we reset...
git reset --hard
git fsck
you will get a dangling blob ce013625030ba8dba906f756967f9e9ca394464a
git show ce01362
will give you the file content "hello" back
To find unreferenced commits I found a tip somewhere suggesting this.
gitk --all $(git log -g --pretty=format:%h)
I have it as a tool in git gui and it is very handy.
Type a value in one cell (EX:B4 CELL). For temporary use this formula in other cell (once done delete it). =CONCAT(XY,B4) . click and drag till the value you need. Copy the whole column and right click paste only values (second option).
I tried and it's working as expected.
Git ignores folders if you write:
/js
but it can't add exceptions if you do:
!/js/jquery
or !/js/jquery/
or !/js/jquery/*
You must write:
/js/*
and only then you can except subfolders like this
!/js/jquery
You could write an extension method called Reset(), which
Here's a gist which does this: https://gist.github.com/dcollien/312bce1270a5f511bf4a
(an es6 version, and a .js version which can be included in a script tag)
You can use it as follows:
<input type="file" id="select">
<img id="preview">
<script>
document.getElementById('select').onchange = function(evt) {
ImageTools.resize(this.files[0], {
width: 320, // maximum width
height: 240 // maximum height
}, function(blob, didItResize) {
// didItResize will be true if it managed to resize it, otherwise false (and will return the original file as 'blob')
document.getElementById('preview').src = window.URL.createObjectURL(blob);
// you can also now upload this blob using an XHR.
});
};
</script>
It includes a bunch of support detection and polyfills to make sure it works on as many browsers as I could manage.
(it also ignores gif images - in case they're animated)
#Use this, THIS IS FOR EXTRACTING NUMBER FROM STRING IN GENERAL. #To get all the numeric occurences.
*split function to convert string to list and then the list comprehension which can help us iterating through the list and is digit function helps to get the digit out of a string.
test_string = "i have four ballons for 2 kids"
print("The original string : "+ test_string)
# list comprehension + isdigit() +split()
res = [int(i) for i in test_string.split() if i.isdigit()]
print("The numbers list is : "+ str(res))
#To extract numeric values from a string in python
*Find list of all integer numbers in string separated by lower case characters using re.findall(expression,string)
method.
*Convert each number in form of string into decimal number and then find max of it.
import re
def extractMax(input):
# get a list of all numbers separated by lower case characters
numbers = re.findall('\d+',input)
# \d+ is a regular expression which means one or more digit
number = map(int,numbers)
print max(numbers)
if __name__=="__main__":
input = 'sting'
extractMax(input)
Try this
double d = 2.22912312515;
int demention = 3;
double truncate = Math.Truncate(d) + Math.Truncate((d - Math.Truncate(d)) * Math.Pow(10.0, demention)) / Math.Pow(10.0, demention);
The size_t
type is defined as the unsigned integral type of the sizeof
operator. In the real world, you will often see int
defined as 32 bits (for backward compatibility) but size_t
defined as 64 bits (so you can declare arrays and structures more than 4 GiB in size) on 64-bit platforms. If a long int
is also 64-bits, this is called the LP64 convention; if long int
is 32 bits but long long int
and pointers are 64 bits, that’s LLP64. You also might get the reverse, a program that uses 64-bit instructions for speed, but 32-bit pointers to save memory. Also, int
is signed and size_t
is unsigned.
There were historically a number of other platforms where addresses were wider or shorter than the native size of int
. In fact, in the ’70s and early ’80s, this was more common than not: all the popular 8-bit microcomputers had 8-bit registers and 16-bit addresses, and the transition between 16 and 32 bits also produced many machines that had addresses wider than their registers. I occasionally still see questions here about Borland Turbo C for MS-DOS, whose Huge memory mode had 20-bit addresses stored in 32 bits on a 16-bit CPU (but which could support the 32-bit instruction set of the 80386); the Motorola 68000 had a 16-bit ALU with 32-bit registers and addresses; there were IBM mainframes with 15-bit, 24-bit or 31-bit addresses. You also still see different ALU and address-bus sizes in embedded systems.
Any time int
is smaller than size_t
, and you try to store the size or offset of a very large file or object in an unsigned int
, there is the possibility that it could overflow and cause a bug. With an int
, there is also the possibility of getting a negative number. If an int
or unsigned int
is wider, the program will run correctly but waste memory.
You should generally use the correct type for the purpose if you want portability. A lot of people will recommend that you use signed math instead of unsigned (to avoid nasty, subtle bugs like 1U < -3
). For that purpose, the standard library defines ptrdiff_t
in <stddef.h>
as the signed type of the result of subtracting a pointer from another.
That said, a workaround might be to bounds-check all addresses and offsets against INT_MAX
and either 0
or INT_MIN
as appropriate, and turn on the compiler warnings about comparing signed and unsigned quantities in case you miss any. You should always, always, always be checking your array accesses for overflow in C anyway.
Correct the ORACLE_HOME path.
There could be two oracle clients in the system.
I had the same issue, the reason being my ORACLE_HOME was pointed to the oracle installation which was not having the tns.ora file.
Changing the ORACLE_HOME to the Oracle directory which is having the tns.ora solved it.
tns.ora lies in client2\network\admin\
Simple way to remove drop down arrow from select
select {_x000D_
/* for Firefox */_x000D_
-moz-appearance: none;_x000D_
/* for Chrome */_x000D_
-webkit-appearance: none;_x000D_
}_x000D_
_x000D_
/* For IE10 */_x000D_
select::-ms-expand {_x000D_
display: none;_x000D_
}
_x000D_
<select>_x000D_
<option>2000</option>_x000D_
<option>2001</option>_x000D_
<option>2002</option>_x000D_
</select>
_x000D_
The best way to get a pure "100% on, 100% off" blink, like the old <blink>
is like this:
.blink {_x000D_
animation: blinker 1s step-start infinite;_x000D_
}_x000D_
_x000D_
@keyframes blinker {_x000D_
50% {_x000D_
opacity: 0;_x000D_
}_x000D_
}
_x000D_
<div class="blink">BLINK</div>
_x000D_
and another way:
$input = array(
'item1' => 'object1',
'item2' => 'object2',
'item-n' => 'object-n'
);
$output = implode(', ', array_map(
function ($v, $k) {
if(is_array($v)){
return $k.'[]='.implode('&'.$k.'[]=', $v);
}else{
return $k.'='.$v;
}
},
$input,
array_keys($input)
));
or:
$output = implode(', ', array_map(
function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
$input,
array_keys($input)
));
This is a simple way that is inefficient, but it's quite reasonable when you don't need anything too complex or you don't have many objects.
Otherwise there are many different algorithms, but most of them are quite complex to implement.
For example, you can use a divide et impera approach in which you cluster objects hierarchically according to their distance and you give to every cluster a bounding box that contains all the items of the cluster. Then you can check which clusters collide and avoid checking pairs of object that belong to clusters that are not colliding/overlapped.
Otherwise, you can figure out a generic space partitioning algorithm to split up in a similar way the objects to avoid useless checks. These kind of algorithms split the collision detection in two phases: a coarse one in which you see what objects maybe colliding and a fine one in which you effectively check single objects. For example, you can use a QuadTree (Wikipedia) to work out an easy solution...
Take a look at the Wikipedia page. It can give you some hints.
On Mac 10.14, the header files don't seem to be installed in the correct place. Rather than changing paths like the other fixes, I was able to just run this:
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
Follow the instructions and it resolved this problem for me.
After pip install spyder
give this command
pip install --upgrade spyder
This command will update all Spyder dependencies.
Now in command prompt(cmd) navigate to the scripts folder in your python directory. In my system the path is C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts so i use the following command in command prompt.
cd C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts
once you are inside scripts directory type spyder3 and press enter and spyder ide starts.
C:\Users\win10\AppData\Local\Programs\Python\Python36-32\Scripts>spyder3
Remember that in order to query the IEnumerable you need to reference system.linq.
It will give you the extension object needed to do:
CaimsList.FirstOrDefault(x=>x.Type =="variableName").toString();
I'm sorry to say that to the best of my knowledge a pure PHP upload progress bar, or even a PHP/Javascript upload progress bar is not possible because of how PHP works. Your best bet is to use some form of Flash uploader.
AFAIK This is because your script is not executed until all the superglobals are populated, which includes $_FILES. By the time your PHP script gets called, the file is fully uploaded.
EDIT: This is no longer true. It was in 2010.
For XAMPP on MACOS or Linux, remove the semicolon in php.ini file after extension=curl.so
For adding some more information, your example will work without the @
symbol (it prevents escaping with \), this way:
string foo = "this \"word\" is escaped!";
It will work both ways but I prefer the double-quote style for it to be easier working, for example, with filenames (with lots of \ in the string).
Just add parameters, split by comma:
UPDATE tablename SET column1 = "value1", column2 = "value2" ....
See also: mySQL manual on UPDATE
If you are on a Windows machine and have the Git installed, you can try the below steps:
Under the [http] section, add the line: sslVerify = false
[http]
sslVerify = false
Create a Composite object
public class CollectiveObject<X, Y>
{
public X FirstObj;
public Y SecondObj;
}
initialize a composite object with any two objects which you willing to send.
CollectiveObject<myobject1, myobject2> collectiveobj =
new CollectiveObject<myobject1, myobject2>();
collectiveobj.FirstObj = myobj1;
collectiveobj.SecondObj = myobj2;
Do serialization
var req = JSONHelper.JsonSerializer`<CollectiveObject<myobject1, `myobject2>>(collectiveobj);`
`
your API must be like
[Route("Add")]
public List<APIAvailibilityDetails> Add([FromBody]CollectiveObject<myobject1, myobject2> collectiveobj)
{ //to do}
http://jsbin.com/qamuyajipo/3/edit?html,output
.circle {
border: 1px solid red;
background-color: #FFFFFF;
height: 100px;
-moz-border-radius:75px;
-webkit-border-radius: 75px;
width: 100px;
}
Use Comparable interface for sorting on the basis of more than one value like age,name,dept_name... For one value use Comparator interface
As per my understanding, this can be done in two ways :
1) You can use Directory Class with Getfiles method and traverse across all files to check our required extension.
Directory.GetFiles("your_folder_path)[i].Contains("*.txt")
2) You can use Path Class with GetExtension Method which takes file path as a parameter and verifies the extension.To get the file path, just have a looping condition that will fetch a single file and return the filepath that can be used for verification.
Path.GetExtension(your_file_path).Equals(".json")
Note : Both the logic has to be inside a looping condition.
Note for Windows users, the jars should be separated by ;
and not :
.
for example:
javac -cp external_libs\lib1.jar;other\lib2.jar;
application.properties
logging.level.org.springframework.web.client=DEBUG
application.yml
logging:
level:
root: WARN
org.springframework.web.client: DEBUG
Or you simply manage it like full IIS by using Jexus Manager for IIS Express, an open source project I work on
Start a site and the process will be launched for you.
Summary
As mentioned by Ignacio, it updates your .config
for you after you update the kernel source, e.g. with git pull
.
It tries to keep your existing options.
Having a script for that is helpful because:
new options may have been added, or old ones removed
the kernel's Kconfig configuration format has options that:
select
depends
Those option relationships make manual config resolution even harder.
Let's modify .config manually to understand how it resolves configurations
First generate a default configuration with:
make defconfig
Now edit the generated .config
file manually to emulate a kernel update and run:
make oldconfig
to see what happens. Some conclusions:
Lines of type:
# CONFIG_XXX is not set
are not mere comments, but actually indicate that the parameter is not set.
For example, if we remove the line:
# CONFIG_DEBUG_INFO is not set
and run make oldconfig
, it will ask us:
Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
When it is over, the .config
file will be updated.
If you change any character of the line, e.g. to # CONFIG_DEBUG_INFO
, it does not count.
Lines of type:
# CONFIG_XXX is not set
are always used for the negation of a property, although:
CONFIG_XXX=n
is also understood as the negation.
For example, if you remove # CONFIG_DEBUG_INFO is not set
and answer:
Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
with N
, then the output file contains:
# CONFIG_DEBUG_INFO is not set
and not:
CONFIG_DEBUG_INFO=n
Also, if we manually modify the line to:
CONFIG_DEBUG_INFO=n
and run make oldconfig
, then the line gets modified to:
# CONFIG_DEBUG_INFO is not set
without oldconfig
asking us.
Configs whose dependencies are not met, do not appear on the .config
. All others do.
For example, set:
CONFIG_DEBUG_INFO=y
and run make oldconfig
. It will now ask us for: DEBUG_INFO_REDUCED
, DEBUG_INFO_SPLIT
, etc. configs.
Those properties did not appear on the defconfig
before.
If we look under lib/Kconfig.debug
where they are defined, we see that they depend on DEBUG_INFO
:
config DEBUG_INFO_REDUCED
bool "Reduce debugging information"
depends on DEBUG_INFO
So when DEBUG_INFO
was off, they did not show up at all.
Configs which are selected
by turned on configs are automatically set without asking the user.
For example, if CONFIG_X86=y
and we remove the line:
CONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y
and run make oldconfig
, the line gets recreated without asking us, unlike DEBUG_INFO
.
This happens because arch/x86/Kconfig
contains:
config X86
def_bool y
[...]
select ARCH_MIGHT_HAVE_PC_PARPORT
and select forces that option to be true. See also: https://unix.stackexchange.com/questions/117521/select-vs-depends-in-kernel-kconfig
Configs whose constraints are not met are asked for.
For example, defconfig
had set:
CONFIG_64BIT=y
CONFIG_RCU_FANOUT=64
If we edit:
CONFIG_64BIT=n
and run make oldconfig
, it will ask us:
Tree-based hierarchical RCU fanout value (RCU_FANOUT) [32] (NEW)
This is because RCU_FANOUT
is defined at init/Kconfig
as:
config RCU_FANOUT
int "Tree-based hierarchical RCU fanout value"
range 2 64 if 64BIT
range 2 32 if !64BIT
Therefore, without 64BIT
, the maximum value is 32
, but we had 64
set on the .config
, which would make it inconsistent.
Bonuses
make olddefconfig
sets every option to their default value without asking interactively. It gets run automatically on make
to ensure that the .config
is consistent in case you've modified it manually like we did. See also: https://serverfault.com/questions/116299/automatically-answer-defaults-when-doing-make-oldconfig-on-a-kernel-tree
make alldefconfig
is like make olddefconfig
, but it also accepts a config fragment to merge. This target is used by the merge_config.sh
script: https://stackoverflow.com/a/39440863/895245
And if you want to automate the .config
modification, that is not too simple: How do you non-interactively turn on features in a Linux kernel .config file?
The JDK provides
Collections.unmodifiableXXX
methods, but in our opinion, these can be unwieldy and verbose; unpleasant to use everywhere you want to make defensive copies unsafe: the returned collections are only truly immutable if nobody holds a reference to the original collection inefficient: the data structures still have all the overhead of mutable collections, including concurrent modification checks, extra space in hash tables, etc.
if you are using 3.6 try this
k = 250
print(f"User pressed the: {k}")
Output: User pressed the: 250
You can use env package to manage your environment variables per project:
.env
file under the project directory and put all of your
variables there.require('dotenv').config();
Done. Now you can access your environment variables with process.env.ENV_NAME
.
Easy:
SELECT SUBSTR(OrderNo, 1, 2) FROM shipment;
Personally I like the navigationDrawer
in Google Drive official app. It just works and works great. I agree that the navigation drawer shouldn't move the action bar because is the key point to open and close the navigation drawer.
If you are still trying to get that behavior I recently create a project Called SherlockNavigationDrawer
and as you may expect is the implementation of the Navigation Drawer with ActionBarSherlock
and works for pre Honeycomb devices. Check it:
You can solve this by unchecking contextswitchdeadlock from
Debug->Exceptions ... -> Expand MDA node -> uncheck -> contextswitchdeadlock
page_path = define in urls.py
def deletePolls(request):
pollId = deletePool(request.GET['id'])
return HttpResponseRedirect("/page_path/")
What is meta_key
? Strip out all of the meta_value
conditionals, reduce, and you end up with this:
SELECT
*
FROM
meta_data
WHERE
(
(meta_key = 'lat')
)
AND
(
(meta_key = 'long')
)
GROUP BY
item_id
Since meta_key
can never simultaneously equal two different values, no results will be returned.
Based on comments throughout this question and answers so far, it sounds like you're looking for something more along the lines of this:
SELECT
*
FROM
meta_data
WHERE
(
(meta_key = 'lat')
AND
(
(meta_value >= '60.23457047672217')
OR
(meta_value <= '60.23457047672217')
)
)
OR
(
(meta_key = 'long')
AND
(
(meta_value >= '24.879140853881836')
OR
(meta_value <= '24.879140853881836')
)
)
GROUP BY
item_id
Note the OR
between the top-level conditionals. This is because you want records which are lat
or long
, since no single record will ever be lat
and long
.
I'm still not sure what you're trying to accomplish by the inner conditionals. Any non-null value will match those numbers. So maybe you can elaborate on what you're trying to do there. I'm also not sure about the purpose of the GROUP BY
clause, but that might be outside the context of this question entirely.
this is one:
ls -l . | egrep -c '^-'
Note:
ls -1 | wc -l
Which means:
ls
: list files in dir
-1
: (that's a ONE) only one entry per line. Change it to -1a if you want hidden files too
|
: pipe output onto...
wc
: "wordcount"
-l
: count l
ines.
Here's the way to extend to variable args when you don't have the args hard coded (although they are still technically hard coded in this example, but should be easy to figure out how to extend...):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int argcount = 3;
const char* args[] = {"1", "2", "3"};
const char* binary_name = "mybinaryname";
char myoutput_array[5000];
sprintf(myoutput_array, "%s", binary_name);
for(int i = 0; i < argcount; ++i)
{
strcat(myoutput_array, " ");
strcat(myoutput_array, args[i]);
}
system(myoutput_array);
Sometimes you want element.constructor.name
document.createElement('div').constructor.name
// HTMLDivElement
document.createElement('a').constructor.name
// HTMLAnchorElement
document.createElement('foo').constructor.name
// HTMLUnknownElement
String path = System.getProperty("user.dir")+"/config.xml";
File f=new File(path);
The command I used with Azure DevOps when I encountered the message "updates were rejected because the tip of your current branch is behind" was/is this command:
git pull origin master
(or can start with a new folder and do a Clone) ..
This answer doesn't address the question posed, specifically, Keif has answered this above, but it does answer the question's title/heading text and this will be a common question for Azure DevOps users.
I noted comment: "You'd always want to make sure that you do a pull before pushing" in answer from Keif above !
I have also used Git Gui tool in addition to Git command line tool.
(I wasn't sure how to do the equivalent of the command line command "git pull origin master" within Git Gui so I'm back to command line to do this).
A diagram that shows various git commands for various actions that you might want to undertake is this one:
In Pandas, I like to use the shape
attribute to get number of rows.
df[df.A > 0].shape[0]
gives the number of rows matching the condition A > 0
, as desired.
As mentioned above, put gem: --no-document
in your gem file. However, the system-wide gemrc will not always necessarily go into /etc/gemrc
. If you are using RVM, or you have Ruby installed under /usr/local/bin
, it needs to go in a different location. You can find this location by running irb
and typing...
require 'rubygems'
Gem::ConfigFile::SYSTEM_WIDE_CONFIG_FILE
See the original post on this over here.
The default HTML editor (for static HTML) doesn't have a design view. To set the default editor to the Web forms editor which does have a design view,
Open with
HTML (web forms) editor
Set as default
OK
buttonOnce you have done that, all you need to do is click on design
or split
view as shown below:
just like in C and C++, the boolean or operator is ||
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
// Do stuff here
}
I decided not to touch headers and make a redirect on the server side instead and it woks like a charm.
The example below is for the current version of Angular (currently 9) and probably any other framework using webpacks DevServer. But I think the same principle will work on other backends.
So I use the following configuration in the file proxy.conf.json:
{
"/api": {
"target": "http://localhost:3000",
"pathRewrite": {"^/api" : ""},
"secure": false
}
}
In case of Angular I serve with that configuration:
$ ng serve -o --proxy-config=proxy.conf.json
I prefer to use the proxy in the serve command, but you may also put this configuration to angular.json like this:
"architect": {
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "your-application-name:build",
"proxyConfig": "src/proxy.conf.json"
},
See also:
https://www.techiediaries.com/fix-cors-with-angular-cli-proxy-configuration/
https://webpack.js.org/configuration/dev-server/#devserverproxy
The package collapse has it built in: %!in%
.
as in this post, using .is
and the attribute selector []
, you can easily add a function (or prototype):
function hasAttr($sel,attr) {
return $sel.is('['+attr+']');
}
df[df['ids'].str.contains('ball', na = False)] # valid for (at least) pandas version 0.17.1
Step-by-step explanation (from inner to outer):
df['ids']
selects the ids
column of the data frame (technically, the object df['ids']
is of type pandas.Series
)df['ids'].str
allows us to apply vectorized string methods (e.g., lower
, contains
) to the Seriesdf['ids'].str.contains('ball')
checks each element of the Series as to whether the element value has the string 'ball' as a substring. The result is a Series of Booleans indicating True
or False
about the existence of a 'ball' substring.df[df['ids'].str.contains('ball')]
applies the Boolean 'mask' to the dataframe and returns a view containing appropriate records.na = False
removes NA / NaN values from consideration; otherwise a ValueError may be returned.Create the following method:
public class Logger {
public static void log(String message) {
PrintWriter out = new PrintWriter(new FileWriter("output.txt", true), true);
out.write(message);
out.close();
}
}
(I haven't included the proper IO handling in the above class, and it won't compile - do it yourself. Also consider configuring the file name. Note the "true" argument. This means the file will not be re-created each time you call the method)
Then instead of System.out.println(str)
call Logger.log(str)
This manual approach is not preferable. Use a logging framework - slf4j, log4j, commons-logging, and many more
You can use a deadlock graph
and gather the information you require from the log file.
The only other way I could suggest is digging through the information by using EXEC SP_LOCK
(Soon to be deprecated), EXEC SP_WHO2
or the sys.dm_tran_locks
table.
SELECT L.request_session_id AS SPID,
DB_NAME(L.resource_database_id) AS DatabaseName,
O.Name AS LockedObjectName,
P.object_id AS LockedObjectId,
L.resource_type AS LockedResource,
L.request_mode AS LockType,
ST.text AS SqlStatementText,
ES.login_name AS LoginName,
ES.host_name AS HostName,
TST.is_user_transaction as IsUserTransaction,
AT.name as TransactionName,
CN.auth_scheme as AuthenticationMethod
FROM sys.dm_tran_locks L
JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
JOIN sys.objects O ON O.object_id = P.object_id
JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE resource_database_id = db_id()
ORDER BY L.request_session_id
http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph
// inVisible
TabPage page2 = tabControl1.TabPages[0];
page2.Visible= false;
//Visible
page2.Visible= true;
// disable
TabPage page2 = tabControl1.TabPages[0];
page2.Enabled = false;
// enable
page2.Enabled = true;
//Hide
tabCtrlTagInfo.TabPages(0).Hide()
tabCtrlTagInfo.TabPages(0).Show()
Just copy paste and try it,the above code has been tested in vs2010, it works.
Simply running easy_install -U pip
resolved my problem.
I arrived here from a google search, since my other code is 'tidy' so leaving the 'tidy' way for anyone who else who may find it useful
library(dplyr)
iris %>%
mutate(Species = ifelse(as.character(Species) == "virginica", "newValue", as.character(Species)))
You can also perform Implicit Type Conversions with template literals. Example:
let fruits = ["mango","orange","pineapple","papaya"];
console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya
Put the divisions in 'td' tag. That's it done.
SQL query to get record of the present month only
SELECT * FROM CUSTOMER
WHERE MONTH(DATE) = MONTH(CURRENT_TIMESTAMP) AND YEAR(DATE) = YEAR(CURRENT_TIMESTAMP);
If you haven't actually registered any users with your existing format then you would be best to switch to using the BCrypt password encoder instead.
It's a lot less hassle, as you don't have to worry about salt at all - the details are completely encapsulated within the encoder. Using BCrypt is stronger than using a plain hash algorithm and it's also a standard which is compatible with applications using other languages.
There's really no reason to choose any of the other options for a new application.
For most installations, you should not set these variables since they are not needed for Python to run. Python knows where to find its standard library.
The only reason to set PYTHONPATH is to maintain directories of custom Python libraries that you do not want to install in the global default location (i.e., the site-packages
directory).
Make sure to read: http://docs.python.org/using/cmdline.html#environment-variables
If you created your script on windows and want to run it on linux machine, and you're sure there is no mistake in your code, install dos2unix on linux machine and run dos2unix yourscript.sh
. Then, run the script.
On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.
You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.
If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.
$(window).height()
$(window).width()
There is also a plugin to jquery to determine element location and offsets
http://plugins.jquery.com/project/dimensions
scrolling offset = offsetHeight property of an element
James Curran succinctly says: "Switches based on integers can be optimized to very efficent code. Switches based on other data type can only be compiled to a series of if() statements. For that reason C & C++ only allow switches on integer types, since it was pointless with other types."
My opinion, and it's only that, is that as soon as you start switching on non-primitives you need to start thinking about "equals" versus "==". Firstly comparing two strings can be a fairly lengthy procedure, adding to the performance problems that are mentioned above. Secondly if there is switching on strings there will be demand for switching on strings ignoring case, switching on strings considering/ignoring locale,switching on strings based on regex.... I would approve of a decision that saved a lot of time for the language developers at the cost of a small amount of time for programmers.
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
You can't do that from the initialization list,
Have a look at this:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
:)
This is the latest async/await
pattern solution.
export async function dataUrlToFile(dataUrl: string, fileName: string): Promise<File> {
const res: Response = await fetch(dataUrl);
const blob: Blob = await res.blob();
return new File([blob], fileName, { type: 'image/png' });
}
To remove & delete all changes git clean -d -f
Redirect standard error. For instance, if you're using bash on a unix machine, you can redirect standard error to /dev/null like this:
find . 2>/dev/null >files_and_folders
Found an easier way to set it. Here's the html and css:
<style>
#body {
*background: url(../Images/abcd.jpg) no-repeat center center fixed; /* For IE 6 and 7 */
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
</style>
<body id="body">
<nav class="navbar navbar-default" id="navColour">
<div class="container-fluid">
<div class="navbar-header">
<a id="clr" class="navbar-brand" href="#">Summer Haze Festival</a>
</div>
<div>
<ul class="nav navbar-nav" >
<li id="clr" class="active"><a href="#">Home</a></li>
<li id="clr"><a href="#">Page 1</a></li>
<li id="clr"><a href="#">Page 2</a></li>
<li id="clr"><a href="#">Page 3</a></li>
</ul>
</div>
</div>
</nav>
</body>
url(../Images/abcd.jpg) being the image stored in your solution in a folder called Images. Hope it helps. Note: I used the id "body" because the navigation bar was somehow overriding my background image.
You can also run ->select('DISTINCT `field`', FALSE)
and the second parameter tells CI
not to escape the first argument.
With the second parameter as false
, the output would be SELECT DISTINCT `field`
instead of without the second parameter, SELECT `DISTINCT` `field`
You can build it with list comprehension like this:
>>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2'])
{'1': [1, 2], '2': [2, 3]}
And for the second part of your question use defaultdict
>>> from collections import defaultdict
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
we can get all the classes by .attr("class")
, and to Array, And loop & filter:
var classArr = $("#sample").attr("class").split(" ")
$("#sample").attr("class", "")
for(var i = 0; i < classArr.length; i ++) {
// some condition/filter
if(classArr[i].substr(0, 5) != "color") {
$("#sample").addClass(classArr[i]);
}
}
The new official AWS CLI natively supports most of the functionality of s3cmd
. I'd previously been using s3cmd
or the ruby AWS SDK to do things like this, but the official CLI works great for this.
http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html
aws s3 sync s3://oldbucket s3://newbucket
On windows Power Shell, you can use the following command:
New-Item <filename.extension>
or
New-Item <filename.extension> -type file
Note: New-Item can be replaced with its alias ni
A = zeros(20, 10, 3); %# Creates a 20x10x3 matrix
B = zeros(4,4);
C = zeros(size(B,1), size(B,2), 4); %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B; %# Copy the content of B into C's first set of values
zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0
for a 3D matrix. To confirm the size of your matrices you can run: size(A)
which gives 20 10 3
.
There is no explicit bound on the number of dimensions a matrix may have.
It happened to me when I had a same port used in ssh tunnel SOCKS to run Proxy in 8080 port and my server and my firefox browser proxy was set to that port and got this issue.
If you're looking for a quick way to do this, for example debugging, you can simply concatenate an empty string on to the boolean:
System.out.println(b+"");
However, I strongly recommend using another method for production usage. This is a simple quick solution which is useful for debugging.
Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64 that I was looking for:
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;
public class TrippleDes {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec ks;
private SecretKeyFactory skf;
private Cipher cipher;
byte[] arrayBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
public TrippleDes() throws Exception {
myEncryptionKey = "ThisIsSpartaThisIsSparta";
myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
ks = new DESedeKeySpec(arrayBytes);
skf = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = skf.generateSecret(ks);
}
public String encrypt(String unencryptedString) {
String encryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] encryptedText = cipher.doFinal(plainText);
encryptedString = new String(Base64.encodeBase64(encryptedText));
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}
public String decrypt(String encryptedString) {
String decryptedText=null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText = Base64.decodeBase64(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText= new String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
return decryptedText;
}
public static void main(String args []) throws Exception
{
TrippleDes td= new TrippleDes();
String target="imparator";
String encrypted=td.encrypt(target);
String decrypted=td.decrypt(encrypted);
System.out.println("String To Encrypt: "+ target);
System.out.println("Encrypted String:" + encrypted);
System.out.println("Decrypted String:" + decrypted);
}
}
Running the above program results with the following output:
String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator
Not sure why the accepted answer doesn't work in my environment, finally I run below command to get what I need
git log --pretty=format:"%h - %an, %ar : %s"|grep "STRING"
it is because of using web address, You can not use http to write data. don't use : http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"]. for example :
wrong :
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')
correct:
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')
Start an export process to create an apk for your app and use your production key. The very last page displays both your SHA1 and MD5 certificate fingerprints
**Adding this for the future me.**
I encountered this because I was reusing Laravel's "HomeController", and adding my custom functions to it. Note that this controller calls the auth
middleware in its __construct()
method as shown below, which means that all functions must be authenticated. No wonder it tries to take you to login page first. So, if you are not using Laravel's authentication scafffolding, you will be in a mess. Disable the constructor, or do as you seem fit, now that you know what is happening.
public function __construct()
{
$this->middleware('auth');
}
var x = y !== undefined ? y : 1;
Note that var x = y || 1;
would assign 1
for any case where y
is falsy (e.g. false
, 0
, ""
), which may be why it "didn't work" for you. Also, if y
is a global variable, if it's truly not defined you may run into an error unless you access it as window.y
.
As vol7ron suggests in the comments, you can also use typeof
to avoid the need to refer to global vars as window.<name>
:
var x = typeof y != "undefined" ? y : 1;
I believe you have libx264
installed and configured with ffmpeg
to convert video to h264
... Then you can try with -vcodec libx264
... The -format
option is for showing available formats, this is not a conversion option I think...
You can download in the current directory with a .
:
cd # by default, goes to $HOME
scp me@host:/path/to/file .
or in you HOME
directly with :
scp me@host:/path/to/file ~
If I correctly got what you want:
$rules = ['Fno' => 'digits_between:2,5', 'Lno' => 'numeric|min:2'];
or
$rules = ['Fno' => 'numeric|min:2|max:5', 'Lno' => 'numeric|min:2'];
For all the available rules: http://laravel.com/docs/4.2/validation#available-validation-rules
digits_between :min,max
The field under validation must have a length between the given min and max.
numeric
The field under validation must have a numeric value.
max:value
The field under validation must be less than or equal to a maximum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.
min:value
The field under validation must have a minimum value. Strings, numerics, and files are evaluated in the same fashion as the size rule.
I followed approach as shown in code below to return a dictionary. Created a class and declared dictionary as global and created a function to add value corresponding to some keys in dictionary.
**Note have used Python 2.7 so some minor modification might be required for Python 3+
class a:
global d
d={}
def get_config(self,x):
if x=='GENESYS':
d['host'] = 'host name'
d['port'] = '15222'
return d
Calling get_config method using class instance in a separate python file:
from constant import a
class b:
a().get_config('GENESYS')
print a().get_config('GENESYS').get('host')
print a().get_config('GENESYS').get('port')
This Statement used in Angular2 Beta version.....
Hereafter use let instead of #
let keyword is used to declare local variable
Of the solutions you mentioned, none of them appear to give you direct access to the MapKit framework introduced in OS 3.0.
As the Google Maps HTML widgets aren't nearly as good as MapKit (see Google Latitude for an example), you are probably best off developing a native Cocoa touch application, or choosing a solution you can extend to add MapKit integration. PhoneGap is extensible in this manner (it's open-source so it is by default), and some of the other solutions might be as well.
edit: Titanium now has support for MapKit
You could utilize jQuery.filter() function to return elements from a subset of the matching elements.
var names = [_x000D_
{ name : "Joe", age:20, email: "[email protected]"},_x000D_
{ name : "Mike", age:50, email: "[email protected]"},_x000D_
{ name : "Joe", age:45, email: "[email protected]"}_x000D_
];_x000D_
_x000D_
_x000D_
var filteredNames = $(names).filter(function( idx ) {_x000D_
return names[idx].name === "Joe" && names[idx].age < 30;_x000D_
}); _x000D_
_x000D_
$(filteredNames).each(function(){_x000D_
$('#output').append(this.name);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="output"/>
_x000D_
The difference comes in when you use the struct
.
The first way you have to do:
struct myStruct aName;
The second way allows you to remove the keyword struct
.
myStruct aName;
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
//alert(html);
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
and the html
<input id="search" style="height:36px; font-size:13px;" type="text" class="form-control" placeholder="Enter Mobile Number or Email" value="<?php echo stripcslashes($_REQUEST["string"]); ?>" name="string" />
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
Here's a comprehensive yet non-exhaustive list of examples of list
operations and whether or not they are thread safe.
Hoping to get an answer regarding the obj in a_list
language construct here.
You have to edit httpd.conf
and find this line: Listen 127.0.0.1:80
Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80
I used 192.167.137.1
as my LAN IP of Windows 7. Restart Apache and enjoy sharing.
@eljenso : intrafest-servlet.xml webapplication context xml will be used if the application uses SPRING WEB MVC.
Otherwise the @kosoant configuration is fine.
Simple example if you dont use SPRING WEB MVC, but want to utitlize SPRING IOC :
In web.xml:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application-context.xml</param-value>
</context-param>
Then, your application-context.xml will contain: <import resource="foo-services.xml"/>
these import statements to load various application context files and put into main application-context.xml.
Thanks and hope this helps.
Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:
^([A-Z]{3})$
The {3}
indicates that the [A-Z]
must appear exactly 3 times.
You need to add a CDATA tag inside of the script tag, unless you want to manually go through and escape all XHTML characters (e.g. &
would need to become &
). For example:
<script>
//<![CDATA[
var el = document.getElementById("pacman");
if (Modernizr.canvas && Modernizr.localstorage &&
Modernizr.audio && (Modernizr.audio.ogg || Modernizr.audio.mp3)) {
window.setTimeout(function () { PACMAN.init(el, "./"); }, 0);
} else {
el.innerHTML = "Sorry, needs a decent browser<br /><small>" +
"(firefox 3.6+, Chrome 4+, Opera 10+ and Safari 4+)</small>";
}
//]]>
</script>
And when I debug this the logic does fall into the sentence.replace.
Yes, and then you discard the return value.
Strings in Java are immutable - when you call replace
, it doesn't change the contents of the existing string - it returns a new string with the modifications. So you want:
sentence = sentence.replace("and", " ");
This applies to all the methods in String (substring
, toLowerCase
etc). None of them change the contents of the string.
Note that you don't really need to do this in a condition - after all, if the sentence doesn't contain "and"
, it does no harm to perform the replacement:
String sentence = "Define, Measure, Analyze, Design and Verify";
sentence = sentence.replace("and", " ");
ALTER TABLE
can do multiple table alterations in one statement, but MODIFY COLUMN
can only work on one column at a time, so you need to specify MODIFY COLUMN
for each column you want to change:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100);
Also, note this warning from the manual:
When you use CHANGE or MODIFY,
column_definition
must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.
CustomRequest is a way to solve the Volley's JSONObjectRequest can't post parameters like the StringRequest
here is the helper class which allow to add params:
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
public class CustomRequest extends Request<JSONObject> {
private Listener<JSONObject> listener;
private Map<String, String> params;
public CustomRequest(String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
public CustomRequest(int method, String url, Map<String, String> params,
Listener<JSONObject> reponseListener, ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = reponseListener;
this.params = params;
}
protected Map<String, String> getParams()
throws com.android.volley.AuthFailureError {
return params;
};
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
@Override
protected void deliverResponse(JSONObject response) {
// TODO Auto-generated method stub
listener.onResponse(response);
}
}
thanks to Greenchiu
None of the above answers is currently working for me. It turns out that .scrollTo
is not as widely compatible as .scrollIntoView
.
In our App.js, in componentWillMount()
we added
this.props.history.listen((location, action) => {
setTimeout(() => { document.getElementById('root').scrollIntoView({ behavior: "smooth" }) }, 777)
})
This is the only solution that is working universally for us. root is the ID of our App. The "smooth" behavior doesn't work on every browser / device. The 777 timeout is a bit conservative, but we load a lot of data on every page, so through testing this was necessary. A shorter 237 might work for most applications.
This enables you to insert a row into 2 different tables and creates a reference to both tables too.
START TRANSACTION;
INSERT INTO accounttable(account_username)
VALUES('AnAccountName');
INSERT INTO profiletable(profile_account_id)
VALUES ((SELECT account_id FROM accounttable WHERE account_username='AnAccountName'));
SET @profile_id = LAST_INSERT_ID();
UPDATE accounttable SET `account_profile_id` = @profile_id;
COMMIT;
for me best solotion this is
Thread.CurrentThread.Abort();
and force close app.
I use this trick to group by one column when I have a multiple columns selection:
SELECT MAX(id) AS id,
Nume,
MAX(intrare) AS intrare,
MAX(iesire) AS iesire,
MAX(intrare-iesire) AS stoc,
MAX(data) AS data
FROM Produse
GROUP BY Nume
ORDER BY Nume
This works.
No, the methods don't need to be synchronized, and you don't need to define any methods; they are already in ConcurrentLinkedQueue, just use them. ConcurrentLinkedQueue does all the locking and other operations you need internally; your producer(s) adds data into the queue, and your consumers poll for it.
First, create your queue:
Queue<YourObject> queue = new ConcurrentLinkedQueue<YourObject>();
Now, wherever you are creating your producer/consumer objects, pass in the queue so they have somewhere to put their objects (you could use a setter for this, instead, but I prefer to do this kind of thing in a constructor):
YourProducer producer = new YourProducer(queue);
and:
YourConsumer consumer = new YourConsumer(queue);
and add stuff to it in your producer:
queue.offer(myObject);
and take stuff out in your consumer (if the queue is empty, poll() will return null, so check it):
YourObject myObject = queue.poll();
For more info see the Javadoc
If you need to block waiting for the queue to not be empty, you probably want to use a LinkedBlockingQueue, and use the take() method. However, LinkedBlockingQueue has a maximum capacity (defaults to Integer.MAX_VALUE, which is over two billion) and thus may or may not be appropriate depending on your circumstances.
If you only have one thread putting stuff into the queue, and another thread taking stuff out of the queue, ConcurrentLinkedQueue is probably overkill. It's more for when you may have hundreds or even thousands of threads accessing the queue at the same time. Your needs will probably be met by using:
Queue<YourObject> queue = Collections.synchronizedList(new LinkedList<YourObject>());
A plus of this is that it locks on the instance (queue), so you can synchronize on queue to ensure atomicity of composite operations (as explained by Jared). You CANNOT do this with a ConcurrentLinkedQueue, as all operations are done WITHOUT locking on the instance (using java.util.concurrent.atomic variables). You will NOT need to do this if you want to block while the queue is empty, because poll() will simply return null while the queue is empty, and poll() is atomic. Check to see if poll() returns null. If it does, wait(), then try again. No need to lock.
Honestly, I'd just use a LinkedBlockingQueue. It is still overkill for your application, but odds are it will work fine. If it isn't performant enough (PROFILE!), you can always try something else, and it means you don't have to deal with ANY synchronized stuff:
BlockingQueue<YourObject> queue = new LinkedBlockingQueue<YourObject>();
queue.put(myObject); // Blocks until queue isn't full.
YourObject myObject = queue.take(); // Blocks until queue isn't empty.
Everything else is the same. Put probably won't block, because you aren't likely to put two billion objects into the queue.
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
To erase 1st element you can use:
vector<int> mV{ 1, 2, 3, 4, 5 };
vector<int>::iterator it;
it = mV.begin();
mV.erase(it);
You can do one thing.
like:- In appsettings.config ->
<appSettings>
<add key="SqlCommandTimeOut" value="240"/>
</appSettings>
In Code ->
command.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);
That should do it.
Note:- I faced most of the timeout issues when I used SqlHelper class from microsoft application blocks. If you have it in your code and are facing timeout problems its better you use sqlcommand and set its timeout as described above. For all other scenarios sqlhelper should do fine. If your client is ok with waiting a little longer than what sqlhelper class offers you can go ahead and use the above technique.
example:- Use this -
SqlCommand cmd = new SqlCommand(completequery);
cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);
SqlConnection con = new SqlConnection(sqlConnectionString);
SqlDataAdapter adapter = new SqlDataAdapter();
con.Open();
adapter.SelectCommand = new SqlCommand(completequery, con);
adapter.Fill(ds);
con.Close();
Instead of
DataSet ds = new DataSet();
ds = SqlHelper.ExecuteDataset(sqlConnectionString, CommandType.Text, completequery);
Update: Also refer to @Triynko answer below. It is important to check that too.
string cannot be the parameter to Nullable because string is not a value type. String is a reference type.
string s = null;
is a very valid statement and there is not need to make it nullable.
private string typeOfContract
{
get { return ViewState["typeOfContract"] as string; }
set { ViewState["typeOfContract"] = value; }
}
should work because of the as keyword.
webDriver.findElement(By.xpath("//*[@id='element']")).isDisplayed();
In real life you wish to simulate a signal with white noise. You should add to your signal random points that have Normal Gaussian distribution. If we speak about a device that have sensitivity given in unit/SQRT(Hz) then you need to devise standard deviation of your points from it. Here I give function "white_noise" that does this for you, an the rest of a code is demonstration and check if it does what it should.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
"""
parameters:
rhp - spectral noise density unit/SQRT(Hz)
sr - sample rate
n - no of points
mu - mean value, optional
returns:
n points of noise signal with spectral noise density of rho
"""
def white_noise(rho, sr, n, mu=0):
sigma = rho * np.sqrt(sr/2)
noise = np.random.normal(mu, sigma, n)
return noise
rho = 1
sr = 1000
n = 1000
period = n/sr
time = np.linspace(0, period, n)
signal_pure = 100*np.sin(2*np.pi*13*time)
noise = white_noise(rho, sr, n)
signal_with_noise = signal_pure + noise
f, psd = signal.periodogram(signal_with_noise, sr)
print("Mean spectral noise density = ",np.sqrt(np.mean(psd[50:])), "arb.u/SQRT(Hz)")
plt.plot(time, signal_with_noise)
plt.plot(time, signal_pure)
plt.xlabel("time (s)")
plt.ylabel("signal (arb.u.)")
plt.show()
plt.semilogy(f[1:], np.sqrt(psd[1:]))
plt.xlabel("frequency (Hz)")
plt.ylabel("psd (arb.u./SQRT(Hz))")
#plt.axvline(13, ls="dashed", color="g")
plt.axhline(rho, ls="dashed", color="r")
plt.show()
here a little script I wrote to convert ascii to hex. hope it helps:
echo '0x'"`echo 'ASCII INPUT GOES HERE' | hexdump -vC | awk 'BEGIN {IFS="\t"} {$1=""; print }' | awk '{sub(/\|.*/,"")}1' | tr -d '\n' | tr -d ' '`" | rev | cut -c 3- | rev
I think that understanding why you can't change the referer
header might help people reading this question.
From this page: https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
From that link:
A forbidden header name is the name of any HTTP header that cannot be modified programmatically...
Modifying such headers is forbidden because the user agent retains full control over them.
Forbidden header names ... are one of the following names:
...
Referer
...
.NET already supports basic Json serialization through the System.Runtime.Serialization.Json namespace and the DataContractJsonSerializer class since version 3.5. As the name implies, DataContractJsonSerializer takes into account any data annotations you add to your objects to create the final Json output.
That can be handy if you already have annotated data classes that you want to serialize Json to a stream, as described in How To: Serialize and Deserialize JSON Data. There are limitations but it's good enough and fast enough if you have basic needs and don't want to add Yet Another Library to your project.
The following code serializea a list to the console output stream. As you see it is a bit more verbose than Json.NET and not type-safe (ie no generics)
var list = new List<string> {"a", "b", "c", "d"};
using(var output = Console.OpenStandardOutput())
{
var writer = new DataContractJsonSerializer(typeof (List<string>));
writer.WriteObject(output,list);
}
On the other hand, Json.NET provides much better control over how you generate Json. This will come in VERY handy when you have to map javascript-friendly names names to .NET classes, format dates to json etc.
Another option is ServiceStack.Text, part of the ServicStack ... stack, which provides a set of very fast serializers for Json, JSV and CSV.
I had the problem not being able to send ">" and ended up with echo!
echo "Hello world" | dd of=test.txt
iframe have "sandbox" attribute that may block pop up etc
I had a similar problem with a rather large workspace in 3.5 and no .snap-files anywhere to be seen. "Windows
-> Preferences
-> General
-> Startup and Shutdown -> Refresh workspace on startup" seems to be a workspace-related setting and so I couldn't change it for the workspace that was causing the hang.
Running eclipse
with the command line parameter -refresh and then changing the setting seems to do the trick.
You are doing it right. The empty code block is what is causing your issue. It's not the condition structure :)
DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME
SET @StartDate = NULL
SET @EndDate = NULL
IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL)
BEGIN
print 'yoyoyo'
END
IF (@StartDate IS NULL AND @EndDate IS NULL AND 1=1 AND 2=2)
BEGIN
print 'Oh hey there'
END
alter table company drop constraint Company_CountryID_FK
That is why the new __dir__()
method has been added in python 2.6
see:
One thing I have observed regarding this error is that is appears only for the first response from the server, which in case of http should be the handshake response. Once an immediate response is sent from the server to the gateway, if after the main response takes time it does not give an error. The key here is that the first response on a request by a server should be fast.
Table with papging, sort and filter
Refer full example at Angularjs table sorting filter and paging
Its works for me.
<style type="text/css">
td {
/* css-3 */
white-space: -o-pre-wrap;
word-wrap: break-word;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
}
And table attribute is:
table {
table-layout: fixed;
width: 100%
}
You can do this with repositories that have been crawled by Google (results vary from repository to repository).
"change license" site:https://github.com/*/*/commits
"change license" site:https://github.com/*/*/commits/master
"change license" site:https://github.com/twitter/*/commits/master
"change license" site:https://github.com/twitter/some_project/commits
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
You can use private as well and you can call private methods with reflection. If you're using Visual Studio Team Suite it has some nice functionality that will generate a proxy to call your private methods for you. Here's a code project article that demonstrates how you can do the work yourself to unit test private and protected methods:
http://www.codeproject.com/KB/cs/testnonpublicmembers.aspx
In terms of which access modifier you should use, my general rule of thumb is start with private and escalate as needed. That way you will expose as little of the internal details of your class as are truly needed and it helps keep the implementation details hidden, as they should be.
It's an argument passed to your success function:
$.ajax({
type: "POST",
url: "somescript.php",
datatype: "html",
data: dataString,
success: function(data) {
alert(data);
}
});
The full signature is success(data, textStatus, XMLHttpRequest)
, but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)
I was also developing a similar application. I was also getting not found error even though the file was there. This solve my problem. I mention my download folder in 'static_folder':
app = Flask(__name__,static_folder='pdf')
My code for the download is as follows:
@app.route('/pdf/<path:filename>', methods=['GET', 'POST'])
def download(filename):
return send_from_directory(directory='pdf', filename=filename)
This is how I am calling my file from html.
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.pdf target="_blank" style="margin-right: 5px;">Download pdf </a>
<a class="label label-primary" href=/pdf/{{ post.hashVal }}.png target="_blank" style="margin-right: 5px;">Download png </a>
Select yourVM -> Settings -> Network ->
Disable the Network Adapter
(It will be re-configured by Genymotion)
Start the Android Image again in Genymotion UI (not in Virtualbox), It should work now!
Consider both at the same time:
Furthermore, I suggest that you expand your Context to include not only access to singleton objects but some functionalities that need to be accessed globally, like for example: context.logOffUser(), context.readSavedData(), etc. Probably renaming the Context to Facade would make sense then.
file --mime works, but not --mime-type. at least for my RHEL 5.