If the device is rooted,
root@mako:/ # settings put global package_verifier_enable 0
Seems to do the trick.
I was able to make the evil eye go away by simply adding this small header to the site in the IFrame (PHP solution):
header('P3P: CP="NOI ADM DEV COM NAV OUR STP"');
Remember to press ctrl+F5 to reload your site or Explorer may still show the evil eye, despite the fact that it's working fine. This is probably the main reason why I had so many problems getting it to work.
No policy file was neccesary at all.
Edit: I found a nice blog entry that explains the problem with cookies in IFrames. It also has a quick fix in C# code: Frames, ASPX Pages and Rejected Cookies
**Reading the Excel File:**
string filePath = @"d:\MyExcel.xlsx";
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
int totalRows = xlRange.Rows.Count;
int totalColumns = xlRange.Columns.Count;
string firstValue, secondValue;
for (int rowCount = 1; rowCount <= totalRows; rowCount++)
{
firstValue = Convert.ToString((xlRange.Cells[rowCount, 1] as Excel.Range).Text);
secondValue = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);
Console.WriteLine(firstValue + "\t" + secondValue);
}
xlWorkBook.Close();
xlApp.Quit();
**Writting the Excel File:**
Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "100";
xlWorkSheet.Cells[2, 2] = "John";
xlWorkSheet.Cells[3, 1] = "101";
xlWorkSheet.Cells[3, 2] = "Herry";
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close();
xlApp.Quit();
'To return the position of an element within any-dimension array
'Returns 0 if the element is not in the array, and -1 if there is an error
Public Function posInArray(ByVal itemSearched As Variant, ByVal aArray As Variant) As Long
Dim pos As Long, item As Variant
posInArray = -1
If IsArray(aArray) Then
If not IsEmpty(aArray) Then
pos = 1
For Each item In aArray
If itemSearched = item Then
posInArray = pos
Exit Function
End If
pos = pos + 1
Next item
posInArray = 0
End If
End If
End Function
Just check the string against this regex:
if(mystring.match(/^\s+$/) === null) {
alert("String is good");
} else {
alert("String contains only whitespace");
}
This URL return to player actual video_id
https://www.youtube.com/embed/live_stream?channel=UCkA21M22vGK9GtAvq3DvSlA
Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.
In jQuery, the $ sign is just an alias to jQuery()
, then an alias to a function.
This page reports:
Basic syntax is: $(selector).action()
- A dollar sign to define jQuery
- A (selector) to "query (or find)" HTML elements
- A jQuery action() to be performed on the element(s)
Best solution can be:
Add a string parameter in the existing job
Then in the Source Code Management
section update Branches to build
to use the string parameter you defined
If you see a checkbox labeled Lightweight checkout
, make sure it is unchecked.
The configuration indicated in the images will tell the jenkins job to use master
as the default branch, and for manual builds it will ask you to enter branch details (FYI: by default it's set to master
)
This is a super old thread but since the answer even says "It doesn't make any sense", I thought I'd add the answer...
The original post used $(this).remove(); in the close handler, this would actually remove the dialog div from the DOM. Attempting to initialize a dialog again wouldn't work because the div was removed.
Using $(this).dialog('destroy') is calling the method destroy defined in the dialog object which does not remove it from the DOM.
From the documentation:
destroy()
Removes the dialog functionality completely. This will return the element back to its >>pre-init state. This method does not accept any arguments.
That said, only destroy or remove on close if you have a good reason to.
This happens when you have Cors option configured at multiple locations. In my case I had it at the controller level as well as in the Startup.Auth.cs/ConfigureAuth.
My understanding is if you want it application wide then just configure it under Startup.Auth.cs/ConfigureAuth like this...You will need reference to Microsoft.Owin.Cors
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
If you rather keep it at the controller level then you may just insert at the Controller level.
[EnableCors("http://localhost:24589", "*", "*")]
public class ProductsController : ApiController
{
ProductRepository _prodRepo;
I've noticed that there is no mention of using a temporary file as intermediate. The following gets around the buffering issues by outputting to a temporary file and allows you to parse the data coming from rsync without connecting to a pty. I tested the following on a linux box, and the output of rsync tends to differ across platforms, so the regular expressions to parse the output may vary:
import subprocess, time, tempfile, re
pipe_output, file_name = tempfile.TemporaryFile()
cmd = ["rsync", "-vaz", "-P", "/src/" ,"/dest"]
p = subprocess.Popen(cmd, stdout=pipe_output,
stderr=subprocess.STDOUT)
while p.poll() is None:
# p.poll() returns None while the program is still running
# sleep for 1 second
time.sleep(1)
last_line = open(file_name).readlines()
# it's possible that it hasn't output yet, so continue
if len(last_line) == 0: continue
last_line = last_line[-1]
# Matching to "[bytes downloaded] number% [speed] number:number:number"
match_it = re.match(".* ([0-9]*)%.* ([0-9]*:[0-9]*:[0-9]*).*", last_line)
if not match_it: continue
# in this case, the percentage is stored in match_it.group(1),
# time in match_it.group(2). We could do something with it here...
There are 3 main possibilities to execute a function:
var callback = function(x, y) {
// "this" may be different depending how you call the function
alert(this);
};
The method you choose depends whether:
Docs for Function.call, Function.apply
Maybe your mobile view port is not set.
Add following meta tag inside <head></head>
to allow menu to work on mobiles.
<meta name=viewport content="width=device-width, initial-scale=1">
With Visual Studio 1.43 (Q1 2020), the Ctrl+K then O keyboard shortcut will work for a file.
See issue 89989:
It should be possible to e.g. invoke the "
Open Active File in New Window
" command and open that file into an empty workspace in the web.
It's because there is no long
in javascript.
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
Install the colorlog package, you can use colors in your log messages immediately:
logger
instance, exactly as you would normally do.DEBUG
and INFO
from the logging module directly.ColoredFormatter
provided
by the colorlog
library.import colorlog
logger = colorlog.getLogger()
logger.setLevel(colorlog.colorlog.logging.DEBUG)
handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter())
logger.addHandler(handler)
logger.debug("Debug message")
logger.info("Information message")
logger.warning("Warning message")
logger.error("Error message")
logger.critical("Critical message")
Just update ColoredFormatter
:
handler.setFormatter(colorlog.ColoredFormatter('%(log_color)s [%(asctime)s] %(levelname)s [%(filename)s.%(funcName)s:%(lineno)d] %(message)s', datefmt='%a, %d %b %Y %H:%M:%S'))
Package:
pip install colorlog
output:
Collecting colorlog
Downloading colorlog-4.6.2-py2.py3-none-any.whl (10.0 kB)
Installing collected packages: colorlog
Successfully installed colorlog-4.6.2
JsonFx can deserialize JSON content into dynamic objects.
Serialize to/from dynamic types (default for .NET 4.0):
var reader = new JsonReader(); var writer = new JsonWriter();
string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = reader.Read(input);
Console.WriteLine(output.array[0]); // 42
string json = writer.Write(output);
Console.WriteLine(json); // {"foo":true,"array":[42,false,"Hello!",null]}
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
Since uintptr_t
is not guaranteed to be there in C++/C++11, if this is a one way conversion you can consider uintmax_t
, always defined in <cstdint>
.
auto real_param = reinterpret_cast<uintmax_t>(param);
To play safe, one could add anywhere in the code an assertion:
static_assert(sizeof (uintmax_t) >= sizeof (void *) ,
"No suitable integer type for conversion from pointer type");
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
echo(var_export($var));
When $var
is boolean variable, true
or false
will be printed out.
As mentioned above
Application.Current.DispatcherUnhandledException will not catch exceptions that are thrown from another thread then the main thread.
That actual depend on how the thread was created
One case that is not handled by Application.Current.DispatcherUnhandledException is System.Windows.Forms.Timer for which Application.ThreadException can be used to handle these if you run Forms on other threads than the main thread you will need to set Application.ThreadException from each such thread
I use the following utils method:
public static final void vibratePhone(Context context, short vibrateMilliSeconds) {
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(vibrateMilliSeconds);
}
Add the following permission to the AndroidManifest file
<uses-permission android:name="android.permission.VIBRATE"/>
You can use overloaded methods in case if you wish to use different types of vibrations (patterns / indefinite) as suggested above.
I use abline()
with extremely wide vertical lines to fill the plot space:
abline(v = xpoints, col = "grey90", lwd = 80)
You have to create the frame, then the ablines, and then plot the points so they are visible on top. You can even use a second abline()
statement to put thin white or black lines over the grey, if desired.
Example:
xpoints = 1:20
y = rnorm(20)
plot(NULL,ylim=c(-3,3),xlim=xpoints)
abline(v=xpoints,col="gray90",lwd=80)
abline(v=xpoints,col="white")
abline(h = 0, lty = 2)
points(xpoints, y, pch = 16, cex = 1.2, col = "red")
Since Python 3.5 this is finally no longer awkward:
>>> b'\xde\xad\xbe\xef'.hex()
'deadbeef'
and reverse:
>>> bytes.fromhex('deadbeef')
b'\xde\xad\xbe\xef'
works also with the mutable bytearray
type.
Reference: https://docs.python.org/3/library/stdtypes.html#bytes.hex
You may try this code for you to take comma separated values / an array of values to get back a JSON from webAPI
public class CategoryController : ApiController
{
public List<Category> Get(String categoryIDs)
{
List<Category> categoryRepo = new List<Category>();
String[] idRepo = categoryIDs.Split(',');
foreach (var id in idRepo)
{
categoryRepo.Add(new Category()
{
CategoryID = id,
CategoryName = String.Format("Category_{0}", id)
});
}
return categoryRepo;
}
}
public class Category
{
public String CategoryID { get; set; }
public String CategoryName { get; set; }
}
Output :
[
{"CategoryID":"4","CategoryName":"Category_4"},
{"CategoryID":"5","CategoryName":"Category_5"},
{"CategoryID":"3","CategoryName":"Category_3"}
]
The tensorflow version can be checked either on terminal or console or in any IDE editer as well (like Spyder or Jupyter notebook, etc)
Simple command to check version:
(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)
>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'
Swift 3.0 Full source code:
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController,AVPlayerViewControllerDelegate
{
var playerController = AVPlayerViewController()
@IBAction func Play(_ sender: Any)
{
let path = Bundle.main.path(forResource: "video", ofType: "mp4")
let url = NSURL(fileURLWithPath: path!)
let player = AVPlayer(url:url as URL)
playerController = AVPlayerViewController()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.didfinishplaying(note:)),name:NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
playerController.player = player
playerController.allowsPictureInPicturePlayback = true
playerController.delegate = self
playerController.player?.play()
self.present(playerController,animated:true,completion:nil)
}
func didfinishplaying(note : NSNotification)
{
playerController.dismiss(animated: true,completion: nil)
let alertview = UIAlertController(title:"finished",message:"video finished",preferredStyle: .alert)
alertview.addAction(UIAlertAction(title:"Ok",style: .default, handler: nil))
self.present(alertview,animated:true,completion: nil)
}
func playerViewController(_ playerViewController: AVPlayerViewController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {
let currentviewController = navigationController?.visibleViewController
if currentviewController != playerViewController
{
currentviewController?.present(playerViewController,animated: true,completion:nil)
}
}
}
CSS is your friend; there is no need for the center tag (not to mention it is quite depreciated) nor the excessive non-breaking spaces. Here is a simple example:
CSS
.images {
text-align:center;
}
.images img {
width:100px;
height:100px;
}
.images div {
width:100px;
text-align:center;
}
.images div span {
display:block;
}
.margin_right {
margin-right:50px;
}
.float {
float:left;
}
.clear {
clear:both;
height:0;
width:0;
}
HTML
<div class="images">
<div class="float margin_right">
<a href="http://xyz.com/hello"><img src="hello.png" width="100px" height="100px" /></a>
<span>This is some text</span>
</div>
<div class="float">
<a href="http://xyz.com/hi"><img src="hi.png" width="100px" height="100px" /></a>
<span>And some more text</span>
</div>
<span class="clear"></span>
</div>
I got this error generating a data frame consisting of timestamps and data:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp))
Adding the suggested solution works for me:
df = pd.DataFrame({'data':value}, index=pd.DatetimeIndex(timestamp), dtype=float))
Thanks Chang She!
Example:
data
2005-01-01 00:10:00 7.53
2005-01-01 00:20:00 7.54
2005-01-01 00:30:00 7.62
2005-01-01 00:40:00 7.68
2005-01-01 00:50:00 7.81
2005-01-01 01:00:00 7.95
2005-01-01 01:10:00 7.96
2005-01-01 01:20:00 7.95
2005-01-01 01:30:00 7.98
2005-01-01 01:40:00 8.06
2005-01-01 01:50:00 8.04
2005-01-01 02:00:00 8.06
2005-01-01 02:10:00 8.12
2005-01-01 02:20:00 8.12
2005-01-01 02:30:00 8.25
2005-01-01 02:40:00 8.27
2005-01-01 02:50:00 8.17
2005-01-01 03:00:00 8.21
2005-01-01 03:10:00 8.29
2005-01-01 03:20:00 8.31
2005-01-01 03:30:00 8.25
2005-01-01 03:40:00 8.19
2005-01-01 03:50:00 8.17
2005-01-01 04:00:00 8.18
data
2005-01-01 00:00:00 7.636000
2005-01-01 01:00:00 7.990000
2005-01-01 02:00:00 8.165000
2005-01-01 03:00:00 8.236667
2005-01-01 04:00:00 8.180000
I got stuck with the same problem and after read and try all the suggestions above I just tried to replace manually this image (which you can find it here) in the CSS after downloaded it and saved in the images folder on my app and voilá, problem solved!
here is the CSS:
.ui-state-default .ui-icon {
background-image: url("../img/ui-icons_888888_256x240.png");
}
Given this route
app.get('/hi/:param1', function(req,res){} );
and given this URL
http://www.google.com/hi/there?qs1=you&qs2=tube
You will have:
req.query
{
qs1: 'you',
qs2: 'tube'
}
req.params
{
param1: 'there'
}
Not an answer to the full question but I think it's worth to mention that in Node.js 10 a new util function called isPromise
was added which checks if an object is a native Promise or not:
const utilTypes = require('util').types
const b_Promise = require('bluebird')
utilTypes.isPromise(Promise.resolve(5)) // true
utilTypes.isPromise(b_Promise.resolve(5)) // false
Probably not the case of everybody but I had the same problem. I was using the last, in my case, the error was because I was using jfrog manage from the company where I am working.
npm config list
The result was
; cli configs
metrics-registry = "https://COMPANYNAME.jfrog.io/COMPANYNAM/api/npm/npm/"
scope = ""
user-agent = "npm/6.3.0 node/v8.11.2 win32 x64"
; userconfig C:\Users\USER\.npmrc
always-auth = true
email = "XXXXXXXXX"
registry = "https://COMPANYNAME.jfrog.io/COMPANYNAME/api/npm/npm/"
; builtin config undefined
prefix = "C:\\Users\\XXXXX\\AppData\\Roaming\\npm"
; node bin location = C:\Program Files\nodejs\node.exe
; cwd = C:\WINDOWS\system32
; HOME = C:\Users\XXXXXX
; "npm config ls -l" to show all defaults.
I solve the problem by using the global metrics.
Wow, so many answers. For solid database versioning you need to version control the code that changes your database. Some CMS offer configuration management tools, such as the one in Drupal 8. Here is an overview with practical steps to arrange your workflow and ensure the database configuration is versioned, even in team environments:
Do you want iteration? itertools.combinations. Common usage:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
If you just need to compute the formula, use math.factorial:
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
In Python 3, use the integer division //
instead of /
to avoid overflows:
return f(n) // f(r) // f(n-r)
6
If you're using C++11 or above, I'd suggest using std::snprintf
over std::strcpy
or std::strncpy
because of its safety (i.e., you determine how many characters can be written to your buffer) and because it null-terminates the string for you (so you don't have to worry about it). It would be like this:
#include <string>
#include <cstdio>
std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, sizeof(tab2), "%s", tmp.c_str());
In C++17, you have this alternative:
#include <string>
#include <cstdio>
#include <iterator>
std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, std::size(tab2), "%s", tmp.c_str());
you can use this command by getting your data. this will extract your data...
select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';
If you want to do that why not go with a while, for ease of mind? :P No, but seriously I didn't know that and seems kinda nice so thanks, nice to know!
Note that to do this you need to do it in the Text attribute you cannot use the content like
<TextBlock>Stuff on line1
Stuff on line 2</TextBlock>
You can check wether an arrow key is pressed by:
$(document).keydown(function(e){
if (e.keyCode > 36 && e.keyCode < 41)
alert( "arrowkey pressed" );
});
Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by
Cannot read property 'foo' of undefined error
Let's take this example structure
const user = {
id: 101,
email: '[email protected]',
personalInfo: {
name: 'Jack',
address: [{
line1: 'westwish st',
line2: 'washmasher',
city: 'wallas',
state: 'WX'
}]
}
}
To be able to access nested arrays, you can write your own array reduce util.
const getNestedObject = (nestedObj, pathArr) => {
return pathArr.reduce((obj, key) =>
(obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}
// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);
// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.
There is also an excellent type handling minimal library typy that does all this for you.
With typy, your code will look like this
const city = t(user, 'personalInfo.address[0].city').safeObject;
Disclaimer: I am the author of this package.
The upside-down A symbol is the universal quantifier from predicate logic. (Also see the more complete discussion of the first-order predicate calculus.) As others noted, it means that the stated assertions holds "for all instances" of the given variable (here, s). You'll soon run into its sibling, the backwards capital E, which is the existential quantifier, meaning "there exists at least one" of the given variable conforming to the related assertion.
If you're interested in logic, you might enjoy the book Logic and Databases: The Roots of Relational Theory by C.J. Date. There are several chapters covering these quantifiers and their logical implications. You don't have to be working with databases to benefit from this book's coverage of logic.
I managed to create a simple console "hello world" with QT Creator
used creator 2.4.1 and QT 4.8.0 on windows 7
two ways to do this
Plain C++
do the following
or
QT Console
example: for QT console "hello world"
file - new file project 'project name '
other projects - QT Console Application
Targets select 'Desktop'
project management - next
code:
#include <QtCore/QCoreApplication>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cout<<" hello world";
return a.exec();
}
ctrl -R to run
compilers used for above MSVC 2010 (QT SDK) , and minGW(QT SDK)
hope this helps someone
As I have just started to use QT recently and also searched the Www for info and examples to get started with simple examples still searching...
Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.
The relevant paragraph:
Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.
This makes lots of sense.
For your specific question.. the o
in the <o:p>
means "Office namespace" so anything following the o:
in a tag means "I'm part of Office namespace" - in case of <o:p>
it just means paragraph, the equivalent of the ordinary <p>
tag.
I assume that every HTML tag has its Office "equivalent" and they have more.
complete
executes after either the success
or error
callback were executed.
Maybe you should check the second parameter complete
offers too. It's a String holding the type of success the ajaxCall had.
The different callbacks are described a little more in detail here jQuery.ajax( options )
I guess you missed the fact that the complete
and the success
function (I know inconsistent API) get different data passed in. success
gets only the data, complete
gets the whole XMLHttpRequest
object. Of course there is no responseText
property on the data string.
So if you replace complete
with success
you also have to replace data.responseText
with data
only.
success
The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status.
complete
The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.
If you need to have access to the whole XMLHttpRequest
object in the success callback I suggest trying this.
var myXHR = $.ajax({
...
success: function(data, status) {
...do whatever with myXHR; e.g. myXHR.responseText...
},
...
});
Can anyone tell me why json_encode adds slashes?
Forward slash characters can cause issues (when preceded by a <
it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.
Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.
It doesn't. In JSON "/"
and "\/"
are equivalent.
The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode
and parseJSON
.
I think I have found an easy hack out.
Delete the file that you have on the local repository (the file that you want updated from the latest commit in the remote server)
And then do a git pull
Because the file is deleted, there will be no conflict
If you are using a router then:
Replace server.listen(yourport, 'localhost');
with server.listen(yourport, 'your ipv4 address');
in my machine it is
server.listen(3000, '192.168.0.3');
Make sure your port is forwarded to your ipv4 address.
On Windows Firewall, tick all on Node.js:Server-side JavaScript.
Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.
Run the below query against the database
select distinct local_net_address, local_tcp_port from sys.dm_exec_connections where local_net_address is not null
The above query shows the local IP as well as the listening Port number
Right from the PHP Docs: PHP 5.3 Windows binaries uses the static version of the MCrypt library, no DLL are needed.
http://php.net/manual/en/mcrypt.requirements.php
But if you really want to download it, just go to the mcrypt sourceforge page
FWIW, here is a sort method for showing which processes are using the most virt memory.
memstat | sort -k 1 -t':' -g -r | less
Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.
function setWidth(width) {
var canvas = document.getElementById("myCanvas");
canvas.width = width;
}
I made a **
automatic-network-drive connector
** using a batch file.
Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!
looks a little bit different but works:
net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES
Thx for the Hint :)
If you are not using any JS build tools/NPM, then you can directly include Jquery as:
import 'https://code.jquery.com/jquery-1.12.4.min.js';
const $ = window.$;
You may skip import(Line 1) if you already included jquery using script tag under head.
For a normal array of elements values only:
function sortArrayOfElements(arrayToSort) {
function compareElements(a, b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
return arrayToSort.sort(compareElements);
}
e.g. 1:
var array1 = [1,2,545,676,64,2,24]
output : [1, 2, 2, 24, 64, 545, 676]
var array2 = ["v","a",545,676,64,2,"24"]
output: ["a", "v", 2, "24", 64, 545, 676]
For an array of objects:
function sortArrayOfObjects(arrayToSort, key) {
function compareObjects(a, b) {
if (a[key] < b[key])
return -1;
if (a[key] > b[key])
return 1;
return 0;
}
return arrayToSort.sort(compareObjects);
}
e.g. 1: var array1= [{"name": "User4", "value": 4},{"name": "User3", "value": 3},{"name": "User2", "value": 2}]
output : [{"name": "User2", "value": 2},{"name": "User3", "value": 3},{"name": "User4", "value": 4}]
Godaddy hosting it seems fixed on .htaccess
, myself it is working
RewriteRule ^(.*)$ index.php/$1 [L]
to
RewriteRule ^(.*)$ index.php?/$1 [QSA,L]
Use:
(/bookstore/book[@location='US'])[1]
This will first get the book elements with the location attribute equal to 'US'. Then it will select the first node from that set. Note the use of parentheses, which are required by some implementations.
Note, this is not the same as /bookstore/book[1][@location='US']
unless the first element also happens to have that location attribute.
Some points:
X
or X&
or X const
&
) the compiler will generate the
default copy-constructor. T const &
or T
or T&
then the
compiler will nevertheless generate a
default non-templated
copy-constructor, even though you may think that it shouldn't because when T = X the declaration matches the copy-constructor declaration.HTH
Try this:
String hourMinute = DateTime.Now.ToString("HH:mm");
Now you will get the time in hour:minute format.
M-^ is copy Text. "M" in my environment is "Esc" key ! not "Ctrl"; so I use Esc + 6 to copy that.
[nano help] Escape-key sequences are notated with the Meta (M-) symbol and can be entered using either the Esc, Alt, or Meta key depending on your keyboard setup.
If you have the product's ID you can use that to create a product object:
$_product = wc_get_product( $product_id );
Then from the object you can run any of WooCommerce's product methods.
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Update
Please review the Codex article on how to write your own shortcode.
Integrating the WooCommerce product data might look something like this:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Your shortcode would then look like [woocommerce_price id="99"]
Example : pg_config not executable / error node-gyp
Solution : On windows just try to add PATH Env -> C:\Program Files\PostgreSQL\12\bin
Work for me, Now i can use npm i pg-promise for example or other dependencies.
try using this api :
URL ": http://maps.googleapis.com/maps/api/geocode/json?latlng="+String.valueOf(yout_lattitude)+","+String.valueOf(your_longitude)
Use next
:
(1..10).each do |a|
next if a.even?
puts a
end
prints:
1
3
5
7
9
For additional coolness check out also redo
and retry
.
Works also for friends like times
, upto
, downto
, each_with_index
, select
, map
and other iterators (and more generally blocks).
For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.
MSSQL requires that variables within procedures be DECLAREd and folks use the @Variable syntax (DECLARE @TEXT VARCHAR(25) = 'text'). Also, MS allows for declares within any block in the procedure, unlike mySQL which requires all the DECLAREs at the top.
While good on the command line, I feel using the "set = @variable" within stored procedures in mySQL is risky. There is no scope and variables live across scope boundaries. This is similar to variables in JavaScript being declared without the "var" prefix, which are then the global namespace and create unexpected collisions and overwrites.
I am hoping that the good folks at mySQL will allow DECLARE @Variable at various block levels within a stored procedure. Notice the @ (at sign). The @ sign prefix helps to separate variable names from table column names - as they are often the same. Of course, one can always add an "v" or "l_" prefix, but the @ sign is a handy and succinct way to have the variable name match the column you might be extracting the data from without clobbering it.
MySQL is new to stored procedures and they have done a good job for their first version. It will be a pleaure to see where they take it form here and to watch the server side aspects of the language mature.
If you really want to use ls
, then format its output using awk:
ls -R /path | awk '
/:$/&&f{s=$0;f=0}
/:$/&&!f{sub(/:$/,"");s=$0;f=1;next}
NF&&f{ print s"/"$0 }'
In my case was the following errors lines:
Signing Identity: "-"
…..mobile.app: resource fork, Finder information, or similar detritus not allowed
Command CodeSign failed with a nonzero exit code
the problem was that in the resources folder I had some files with .png extension, which was hidden on the defaults.
Find file in FINDER, mark it -> cmd+i -> unchek Hide extension
after that, return in Xcode -> kmd + shift + K and rebuild.
I hope I've been helpful!
I didn't get the interrupt to work in Android, so I used this method, works perfectly:
boolean shouldCheckUpdates = true;
private void startupCheckForUpdatesEveryFewSeconds() {
threadCheckChat = new Thread(new CheckUpdates());
threadCheckChat.start();
}
private class CheckUpdates implements Runnable{
public void run() {
while (shouldCheckUpdates){
System.out.println("Do your thing here");
}
}
}
public void stop(){
shouldCheckUpdates = false;
}
There's also a package called bit
that is specifically designed for fast boolean operations. It's especially useful if you have large vectors or need to do many boolean operations.
z <- sample(c(TRUE, FALSE), 1e8, rep = TRUE)
system.time({
sum(z) # 0.170s
})
system.time({
bit::sum.bit(z) # 0.021s, ~10x improvement in speed
})
To obtain readable x tick labels without additional dependencies, you want to use:
... +
theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)) +
...
This rotates the tick labels 90° counterclockwise and aligns them vertically at their end (hjust = 1
) and their centers horizontally with the corresponding tick mark (vjust = 0.5
).
Full example:
library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))
q <- qplot(cut,carat,data=diamonds,geom="boxplot")
q + theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
Note, that vertical/horizontal justification parameters vjust
/hjust
of element_text
are relative to the text. Therefore, vjust
is responsible for the horizontal alignment.
Without vjust = 0.5
it would look like this:
q + theme(axis.text.x = element_text(angle = 90, hjust = 1))
Without hjust = 1
it would look like this:
q + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
If for some (wired) reason you wanted to rotate the tick labels 90° clockwise (such that they can be read from the left) you would need to use: q + theme(axis.text.x = element_text(angle = -90, vjust = 0.5, hjust = -1))
.
All of this has already been discussed in the comments of this answer but I come back to this question so often, that I want an answer from which I can just copy without reading the comments.
Here is the code for compling and running java source code: - Open Notepadd++ - Hit F6 - Paste this code
npp_save <-- Saves the current document
CD $(CURRENT_DIRECTORY) <-- Moves to the current directory
javac "$(FILE_NAME)" <-- compiles your file named *.java
java "$(NAME_PART)" <-- executes the program
The Java Classpath variable has to be set for this...
Another useful site: http://www.scribd.com/doc/52238931/Notepad-Tutorial-Compile-and-Run-Java-Program
To properly format numbers in columns, it's best to use printf. Depending on how big are the max or min numbers, you might want to adjust the pattern "%4d"
. For instance to allow any integer between Integer.MIN_VALUE
and Integer.MAX_VALUE
, use "%12d"
.
public void printMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.printf("%4d", matrix[row][col]);
}
System.out.println();
}
}
Example output:
36 913 888 908
732 626 61 237
5 8 50 265
192 232 129 307
You could add this utility function to a utility class:
public static <K, V> Map<K, V> mapOf(Object... keyValues) {
Map<K, V> map = new HashMap<>();
for (int index = 0; index < keyValues.length / 2; index++) {
map.put((K)keyValues[index * 2], (V)keyValues[index * 2 + 1]);
}
return map;
}
Map<Integer, String> map1 = YourClass.mapOf(1, "value1", 2, "value2");
Map<String, String> map2 = YourClass.mapOf("key1", "value1", "key2", "value2");
Note: in Java 9
you can use Map.of
You can free memory used by vector by this way:
//Removes all elements in vector
v.clear()
//Frees the memory which is not used by the vector
v.shrink_to_fit();
A bearer token is like a currency note e.g 100$ bill . One can use the currency note without being asked any/many questions.
Bearer Token A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
Check if ceil function and floor function returns the same value
static boolean isInteger(int n)
{
return (int)(Math.ceil(n)) == (int)(Math.floor(n));
}
if you add a jpg,png,pdf picture, you should use pdflatex to compile it.
import java.io.*;
public class FileRead {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");
OutputStream oos = new FileOutputStream("test.pdf");
byte[] buf = new byte[8192];
InputStream is = new FileInputStream(f);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
System.out.println("stop");
is.close();
}
}
The easiest way so far. Hope this helps.
You need use patches.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
patches.Rectangle(
(0.1, 0.1),
0.5,
0.5,
fill=False # remove background
) )
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')
New Line XML
with XML



or try like @dj_segfault proposed (see his answer) with CDATA;
<![CDATA[Tootsie roll tiramisu macaroon wafer carrot cake.
Danish topping sugar plum tart bonbon caramels cake.]]>
Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.
1: @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)
will both produce
<input id="Name" name="Name" type="text" />
So what does that mean in terms of use?
Generally two things:
TextBoxFor
will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'TextBoxFor
version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.
This is my way. I opened a file in DOS EOL and when I save the file, that will automatically convert to Unix EOL:
autocmd BufWrite * :set ff=unix
if you happened to use NLog in your ASP.net project, you can add a Debugger target:
<targets>
<target name="debugger" xsi:type="Debugger"
layout="${date:format=HH\:mm\:ss}|${pad:padding=5:inner=${level:uppercase=true}}|${message} "/>
and writes logs to this target for the levels you want:
<rules>
<logger name="*" minlevel="Trace" writeTo="debugger" />
now you have console output just like Jetty in "Output" window of VS, and make sure you are running in Debug Mode(F5).
const object1 = {
a: 'somestring',
b: 42
};
for (let [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
// expected output:
// "a: somestring"
// "b: 42"
// order is not guaranteed
My solution was the following:
document.getElementById("agent_details").scrollIntoView();
From here and d5e5's comment:
You'll have to switch the output to csv-mode and switch to file output.
sqlite> .mode csv
sqlite> .output test.csv
sqlite> select * from tbl1;
sqlite> .output stdout
SHA and AES serve different purposes. SHA is used to generate a hash of data and AES is used to encrypt data.
Here's an example of when an SHA hash is useful to you. Say you wanted to download a DVD ISO image of some Linux distro. This is a large file and sometimes things go wrong - so you want to validate that what you downloaded is correct. What you would do is go to a trusted source (such as the offical distro download point) and they typically have the SHA hash for the ISO image available. You can now generated the comparable SHA hash (using any number of open tools) for your downloaded data. You can now compare the two hashs to make sure they match - which would validate that the image you downloaded is correct. This is especially important if you get the ISO image from an untrusted source (such as a torrent) or if you are having trouble using the ISO and want to check if the image is corrupted.
As you can see in this case the SHA has was used to validate data that was not corrupted. You have every right to see the data in the ISO.
AES, on the other hand, is used to encrypt data, or prevent people from viewing that data with knowing some secret.
AES uses a shared key which means that the same key (or a related key) is used to encrypted the data as is used to decrypt the data. For example if I encrypted an email using AES and I sent that email to you then you and I would both need to know the shared key used to encrypt and decrypt the email. This is different than algorithms that use a public key such PGP or SSL.
If you wanted to put them together you could encrypt a message using AES and then send along an SHA1 hash of the unencrypted message so that when the message was decrypted they were able to validate the data. This is a somewhat contrived example.
If you want to know more about these some Wikipedia search terms (beyond AES and SHA) you want want to try include:
Symmetric-key algorithm (for AES) Cryptographic hash function (for SHA) Public-key cryptography (for PGP and SSL)
This will work as long as the image you want to rotate is already in your Properties resources folder.
In Partial Class:
Bitmap bmp2;
OnLoad:
bmp2 = new Bitmap(Tycoon.Properties.Resources.save2);
pictureBox6.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox6.Image = bmp2;
Button or Onclick
private void pictureBox6_Click(object sender, EventArgs e)
{
if (bmp2 != null)
{
bmp2.RotateFlip(RotateFlipType.Rotate90FlipNone);
pictureBox6.Image = bmp2;
}
}
To insert a VARCHAR2
into a BLOB
column you can rely on the function utl_raw.cast_to_raw
as next:
insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));
It will cast your input VARCHAR2
into RAW
datatype without modifying its content, then it will insert the result into your BLOB
column.
More details about the function utl_raw.cast_to_raw
var upload = multer({dest: "./uploads"});
var mongo = require('mongodb');
var Grid = require("gridfs-stream");
Grid.mongo = mongo;
router.post('/:id', upload.array('photos', 200), function(req, res, next){
gfs = Grid(db);
var ss = req.files;
for(var j=0; j<ss.length; j++){
var originalName = ss[j].originalname;
var filename = ss[j].filename;
var writestream = gfs.createWriteStream({
filename: originalName
});
fs.createReadStream("./uploads/" + filename).pipe(writestream);
}
});
In your view:
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="photos">
With this code you can add single as well as multiple images in MongoDB.
Or this in windows powershell
$env:RANDFILE=".rnd"
You can try using .net:
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computer1)
$RegKey= $Reg.OpenSubKey("SOFTWARE\\Veritas\\NetBackup\\CurrentVersion")
$NetbackupVersion1 = $RegKey.GetValue("PackageVersion")
This is the code I'm using. Also works for .NET Core
> 2.0 using System.Drawing.Common
NuGet.
https://www.nuget.org/packages/System.Drawing.Common/
using System;
using System.Drawing;
class Program
{
static void Main()
{
const string input = "C:\\background1.png";
const string output = "C:\\thumbnail.png";
// Load image.
Image image = Image.FromFile(input);
// Compute thumbnail size.
Size thumbnailSize = GetThumbnailSize(image);
// Get thumbnail.
Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
thumbnailSize.Height, null, IntPtr.Zero);
// Save thumbnail.
thumbnail.Save(output);
}
static Size GetThumbnailSize(Image original)
{
// Maximum size of any dimension.
const int maxPixels = 40;
// Width and height.
int originalWidth = original.Width;
int originalHeight = original.Height;
// Return original size if image is smaller than maxPixels
if (originalWidth <= maxPixels || originalHeight <= maxPixels)
{
return new Size(originalWidth, originalHeight);
}
// Compute best factor to scale entire image based on larger dimension.
double factor;
if (originalWidth > originalHeight)
{
factor = (double)maxPixels / originalWidth;
}
else
{
factor = (double)maxPixels / originalHeight;
}
// Return thumbnail size.
return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
}
}
Source:
while on branch master:
git reset --hard origin/master
then do some clean up with git gc
(more about this in the man pages)
Update: You will also probably need to do a git fetch origin
(or git fetch origin master
if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)
// let timeObject = new Date();
// let milliseconds= 10 * 1000; // 10 seconds = 10000 milliseconds
timeObject = new Date(timeObject.getTime() + milliseconds);
The new line character is \n
, like so:
echo __("Thanks for your email.\n<br />\n<br />Your order's details are below:", 'jigoshop');
Throw an IllegalArgumentException with variable in current scope (illarg):
throw new IllegalArgumentException(${var});
Better
throw new IllegalArgumentException("Invalid ${var} " + ${var});
Finally, it happened GitHub has officially announced their new CLI for all the core features.
check here: https://cli.github.com/
To install via HomeBrew: brew install gh
for other Ways : https://github.com/cli/cli#installation
then
gh repo create
Other available features.
$ gh --help
Work seamlessly with GitHub from the command line.
USAGE
gh <command> <subcommand> [flags]
CORE COMMANDS
gist: Create gists
issue: Manage issues
pr: Manage pull requests
release: Manage GitHub releases
repo: Create, clone, fork, and view repositories
ADDITIONAL COMMANDS
alias: Create command shortcuts
api: Make an authenticated GitHub API request
auth: Login, logout, and refresh your authentication
completion: Generate shell completion scripts
config: Manage configuration for gh
help: Help about any command
FLAGS
--help Show help for command
--version Show gh version
EXAMPLES
$ gh issue create
$ gh repo clone cli/cli
$ gh pr checkout 321
ENVIRONMENT VARIABLES
See 'gh help environment' for the list of supported environment variables.
LEARN MORE
Use 'gh <command> <subcommand> --help' for more information about a command.
Read the manual at https://cli.github.com/manual
FEEDBACK
Open an issue using 'gh issue create -R cli/cli'
So now you can create repo from your terminal.
You need to commit or destroy any unsaved changes before you switch branch.
Git won't let you switch branch if it means unsaved changes would be removed.
Try adding
@RequestMapping(method = RequestMethod.GET,headers = {"Accept=text/xml, application/json"})
on getShopInJSON()
.
It worked for me.
I have created a user defined function to mimic the string.format functionality. You can use it.
UPDATE:
This version allows the user to change the delimitter.
-- DROP function will loose the security settings.
IF object_id('[dbo].[svfn_FormatString]') IS NOT NULL
DROP FUNCTION [dbo].[svfn_FormatString]
GO
CREATE FUNCTION [dbo].[svfn_FormatString]
(
@Format NVARCHAR(4000),
@Parameters NVARCHAR(4000),
@Delimiter CHAR(1) = ','
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
/*
Name: [dbo].[svfn_FormatString]
Creation Date: 12/18/2020
Purpose: Returns the formatted string (Just like in C-Sharp)
Input Parameters: @Format = The string to be Formatted
@Parameters = The comma separated list of parameters
@Delimiter = The delimitter to be used in the formatting process
Format: @Format = N'Hi {0}, Welcome to our site {1}. Thank you {0}'
@Parameters = N'Karthik,google.com'
@Delimiter = ','
Examples:
SELECT dbo.svfn_FormatString(N'Hi {0}, Welcome to our site {1}. Thank you {0}', N'Karthik,google.com', default)
SELECT dbo.svfn_FormatString(N'Hi {0}, Welcome to our site {1}. Thank you {0}', N'Karthik;google.com', ';')
*/
DECLARE @Message NVARCHAR(400)
DECLARE @ParamTable TABLE ( Id INT IDENTITY(0,1), Paramter VARCHAR(1000))
SELECT @Message = @Format
;WITH CTE (StartPos, EndPos) AS
(
SELECT 1, CHARINDEX(@Delimiter, @Parameters)
UNION ALL
SELECT EndPos + (LEN(@Delimiter)), CHARINDEX(@Delimiter, @Parameters, EndPos + (LEN(@Delimiter)))
FROM CTE
WHERE EndPos > 0
)
INSERT INTO @ParamTable ( Paramter )
SELECT
[Id] = SUBSTRING(@Parameters, StartPos, CASE WHEN EndPos > 0 THEN EndPos - StartPos ELSE 4000 END )
FROM CTE
UPDATE @ParamTable
SET
@Message = REPLACE(@Message, '{'+ CONVERT(VARCHAR, Id) + '}', Paramter )
RETURN @Message
END
Thats where asp.net puts dynamically compiled assemblies.
The default modifier is package
. Only code in the same package will be able to invoke this constructor.
Answer posted here - same solution to your problem.
Edit: the JQuery answer is very nice if you want a smooth scroll - I hadn't seen that in action before.
Curiously, this works:
yourcommand &> filename
But this gives a syntax error:
yourcommand &>> filename
syntax error near unexpected token `>'
You have to use:
yourcommand 1>> filename 2>&1
For python2/3, Using below code snippet we can activate virtual env.
activate_this = "/home/<--path-->/<--virtual env name -->/bin/activate_this.py" #for ubuntu
activate_this = "D:\<-- path -->\<--virtual env name -->\Scripts\\activate_this.py" #for windows
with open(activate_this) as f:
code = compile(f.read(), activate_this, 'exec')
exec(code, dict(__file__=activate_this))
Sample:
Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;
It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).
One way around this is to bind your event handler in javascript (where it should be):
document.getElementById('optionID').onchange = function () {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:
window.changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
?
I was comparing worldcitiesdatabae.info with www.worldcitiesdatabase.com and it appears the latter one to be more resourceful. However, maxmind has a free database so then why buy a cities database. Just get the free one and there is lot of help available on internet about maxmind db. If you put in extra efforts then you can save those few bucks :)
If you're on Windows Node.js does some funny business when handling quotes that may result in you issuing a command that you know works from the console, but does not when run in Node. For example the following should work:
spawn('ping', ['"8.8.8.8"'], {});
but fails. There's a fantastically undocumented option windowsVerbatimArguments
for handling quotes/similar that seems to do the trick, just be sure to add the following to your opts object:
const opts = {
windowsVerbatimArguments: true
};
and your command should be back in business.
spawn('ping', ['"8.8.8.8"'], { windowsVerbatimArguments: true });
if (!$variablename) { Write-Host "variable is null" }
I hope this simple answer will is resolve the question. Source
1) Go to (Open) Command Prompt (Press Window + R then type cmd Run this).
2) Run following commands
For all listening ports
Apply port filter
Finally with the PID we can run the following command to kill the process
3) Copy PID from result set
Ex: taskkill /F /PID 189
Done !!! you can start your service now.
First, you use include_directories()
to tell CMake to add the directory as -I
to the compilation command line. Second, you list the headers in your add_executable()
or add_library()
call.
As an example, if your project's sources are in src
, and you need headers from include
, you could do it like this:
include_directories(include)
add_executable(MyExec
src/main.c
src/other_source.c
include/header1.h
include/header2.h
)
A simple alternative to this is to use threads along with join. Refer : Joining Threads
If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout
value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.
For example:
// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;
This value can also be configured in your web.config
file in the httpRuntime
configuration element:
<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300"
... other configuration attributes ...
/>
Please note according to the MSDN documentation:
"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."
If you've already done this but are finding that your session is expiring then increase the
ASP.NET HttpSessionState.Timeout
value:
For example:
// Increase session timeout to thirty minutes
Session.Timeout = 30;
This value can also be configured in your web.config
file in the sessionState
configuration element:
<configuration>
<system.web>
<sessionState
mode="InProc"
cookieless="true"
timeout="30" />
</system.web>
</configuration>
If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.
The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.
Regex.Replace(strInput, strToken.Replace("$", "[$]"), strReplaceWith, RegexOptions.IgnoreCase);
This will delete the dataframe and will release the RAM/memory
del [[df_1,df_2]]
gc.collect()
df_1=pd.DataFrame()
df_2=pd.DataFrame()
the data-frame will be explicitly set to null
in the above statements
Firstly, the self reference of the dataframe is deleted meaning the dataframe is no longer available to python there after all the references of the dataframe is collected by garbage collector (gc.collect()) and then explicitly set all the references to empty dataframe.
more on the working of garbage collector is well explained in https://stackify.com/python-garbage-collection/
The clearfix
allows a container to wrap its floated children. Without a clearfix
or equivalent styling, a container does not wrap around its floated children and collapses, just as if its floated children were positioned absolutely.
There are several versions of the clearfix, with Nicolas Gallagher and Thierry Koblentz as key authors.
If you want support for older browsers, it's best to use this clearfix :
.clearfix:before, .clearfix:after {
content: "";
display: table;
}
.clearfix:after {
clear: both;
}
.clearfix {
*zoom: 1;
}
In SCSS, you could use the following technique :
%clearfix {
&:before, &:after {
content:" ";
display:table;
}
&:after {
clear:both;
}
& {
*zoom:1;
}
}
#clearfixedelement {
@extend %clearfix;
}
If you don't care about supporting older browsers, there's a shorter version :
.clearfix:after {
content:"";
display:table;
clear:both;
}
No, the dataType
option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify
and set the processData
option to false
.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON
object, and although jQuery has .parseJSON
, it has no stringifier included; you'll need another polyfill library.
Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )
I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)
By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.
(Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)
There's the NUMBERFORMATTER jQuery plugin, details below:
https://code.google.com/p/jquery-numberformatter/
From the above link:
This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.
EDIT: Replaced the link with a more direct one.
You can paste these methods in the ViewController of each view that needs to be portrait:
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
please don't use a global var for this - store the prev value at the data here is an example: http://jsbin.com/uqupu3/2/edit
the code for ref:
$(document).ready(function(){
var sel = $("#sel");
sel.data("prev",sel.val());
sel.change(function(data){
var jqThis = $(this);
alert(jqThis.data("prev"));
jqThis.data("prev",jqThis.val());
});
});
just saw that you have many selects on page - this approach will also work for you since for each select you will store the prev value on the data of the select
This should do the trick retrieving the params from the url:
constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe(params => {
let date = params['startdate'];
console.log(date); // Print the parameter to the console.
});
}
The local variable date should now contain the startdate parameter from the URL. The modules Router and Params can be removed (if not used somewhere else in the class).
alternatively you can also do this:
p '< echo "x y"' w impulse
x and y are the coordinates of the point to which you draw a vertical bar
I would use a decimal with the proper precision for your data.
It might be due to "client profile" of the .NET Framework. Try to use the "full version" of .NET.
I had the same problem in Google App Scripts, and solved it like the rest said, but with a little more..
function refreshGrid(entity) {
var store = window.localStorage;
var partitionKey;
if (condition) {
return Browser.msgBox("something");
}
}
This way you not only exit the function, but show a message saying why it stopped. Hope it helps.
Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.
You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:
$('#add_comment').click(function() {
if(typeof TinyMCE == "undefined") {
$.getScript('tinymce.js', function() {
TinyMCE.init();
});
}
});
Assuming you only have to call init
on it once, that is. If not, you can figure it out from here :)
the Headers word are not case sensitive, but on the right like the Content-Type, is good practice to write it this way, because its case sensitve. like my example below
headers = headers.set('Content-Type'
I'm getting an index out of range error with the accepted answer solution. Reason: When range start, it is not iterate value one by one, it is iterate by index. If you modified a slice while it is in range, it will induce some problem.
Old Answer:
chars := []string{"a", "a", "b"}
for i, v := range chars {
fmt.Printf("%+v, %d, %s\n", chars, i, v)
if v == "a" {
chars = append(chars[:i], chars[i+1:]...)
}
}
fmt.Printf("%+v", chars)
Expected :
[a a b], 0, a
[a b], 0, a
[b], 0, b
Result: [b]
Actual:
// Autual
[a a b], 0, a
[a b], 1, b
[a b], 2, b
Result: [a b]
Correct Way (Solution):
chars := []string{"a", "a", "b"}
for i := 0; i < len(chars); i++ {
if chars[i] == "a" {
chars = append(chars[:i], chars[i+1:]...)
i-- // form the remove item index to start iterate next item
}
}
fmt.Printf("%+v", chars)
Source: https://dinolai.com/notes/golang/golang-delete-slice-item-in-range-problem.html
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table{_x000D_
border-spacing: 16px 4px;_x000D_
}_x000D_
_x000D_
td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:100%">_x000D_
<tr>_x000D_
<td>Jill</td>_x000D_
<td>Smith</td> _x000D_
<td>50</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Eve</td>_x000D_
<td>Jackson</td> _x000D_
<td>94</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>John</td>_x000D_
<td>Doe</td> _x000D_
<td>80</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Using padding is not correct way of doing it, it may change the look but it is not what you wanted. This may solve your issue.
This won't work. You first have to initialize the array. So far, you only have a String[] reference, pointing to null
.
When you try to read the length member, what you actually do is null.length
, which results in a NullPointerException.
To enable Api do this
API Manager
Overview
Google Maps JavaScript API
(Under Google Maps APIs
). Click on thatEnable
button there. Click to enable API.OR You can try this url: Maps JavaScript API
Hope this will solve the problem of enabling API.
If:
X is image width,
Y is image height,
then:
img {
position: absolute;
top: 50%;
left: 50%;
margin-left: -(X/2)px;
margin-top: -(Y/2)px;
}
But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.
Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.
I gave it a try a while back (also: on GitHub). My implementation had some problems, which I won't get into here. Let me tell you, more importantly, what I learned.
Firstly, there's no way you're going to get a full implementation of IList<T>
that is lockless and thread-safe. In particular, random insertions and removals are not going to work, unless you also forget about O(1) random access (i.e., unless you "cheat" and just use some sort of linked list and let the indexing suck).
What I thought might be worthwhile was a thread-safe, limited subset of IList<T>
: in particular, one that would allow an Add
and provide random read-only access by index (but no Insert
, RemoveAt
, etc., and also no random write access).
This was the goal of my ConcurrentList<T>
implementation. But when I tested its performance in multithreaded scenarios, I found that simply synchronizing adds to a List<T>
was faster. Basically, adding to a List<T>
is lightning fast already; the complexity of the computational steps involved is miniscule (increment an index and assign to an element in an array; that's really it). You would need a ton of concurrent writes to see any sort of lock contention on this; and even then, the average performance of each write would still beat out the more expensive albeit lockless implementation in ConcurrentList<T>
.
In the relatively rare event that the list's internal array needs to resize itself, you do pay a small cost. So ultimately I concluded that this was the one niche scenario where an add-only ConcurrentList<T>
collection type would make sense: when you want guaranteed low overhead of adding an element on every single call (so, as opposed to an amortized performance goal).
It's simply not nearly as useful a class as you would think.
I believe telnet 74.255.12.25 8089
. Why don't u try both
The mail server on CentOS 6 and other IPv6 capable server platforms may be bound to IPv6 localhost (::1) instead of IPv4 localhost (127.0.0.1).
Typical symptoms:
[root@host /]# telnet 127.0.0.1 25
Trying 127.0.0.1...
telnet: connect to address 127.0.0.1: Connection refused
[root@host /]# telnet localhost 25
Trying ::1...
Connected to localhost.
Escape character is '^]'.
220 host ESMTP Exim 4.72 Wed, 14 Aug 2013 17:02:52 +0100
[root@host /]# netstat -plant | grep 25
tcp 0 0 :::25 :::* LISTEN 1082/exim
If this happens, make sure that you don't have two entries for localhost
in /etc/hosts
with different IP addresses, like this (bad) example:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost.localdomain localhost localhost4.localdomain4 localhost4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
To avoid confusion, make sure you only have one entry for localhost
, preferably an IPv4 address, like this:
[root@host /]# cat /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4.localdomain4 localhost4
::1 localhost6 localhost6.localdomain6
I just had this happen to me: I was getting the error only on my device and the simulator was working fine. I ended up having to reset my device and the error went away.
I solved this problem following vestigal's tips here:
Can I set an unlimited length for maxJsonLength in web.config?
When I needed to post a large json to an action in a controller, I would get the famous "Error during deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.\r\nParameter name: input value provider".
What I did is create a new ValueProviderFactory, LargeJsonValueProviderFactory, and set the MaxJsonLength = Int32.MaxValue in the GetDeserializedObject method
public sealed class LargeJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(LargeJsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
{
IDictionary<string, object> dictionary = value as IDictionary<string, object>;
if (dictionary != null)
{
foreach (KeyValuePair<string, object> keyValuePair in (IEnumerable<KeyValuePair<string, object>>) dictionary)
LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
}
else
{
IList list = value as IList;
if (list != null)
{
for (int index = 0; index < list.Count; ++index)
LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakeArrayKey(prefix, index), list[index]);
}
else
backingStore.Add(prefix, value);
}
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return (object) null;
string end = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
if (string.IsNullOrEmpty(end))
return (object) null;
var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};
return serializer.DeserializeObject(end);
}
/// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
/// <returns>A JSON value-provider object for the specified controller context.</returns>
/// <param name="controllerContext">The controller context.</param>
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
object deserializedObject = LargeJsonValueProviderFactory.GetDeserializedObject(controllerContext);
if (deserializedObject == null)
return (IValueProvider) null;
Dictionary<string, object> dictionary = new Dictionary<string, object>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase);
LargeJsonValueProviderFactory.AddToBackingStore(new LargeJsonValueProviderFactory.EntryLimitedDictionary((IDictionary<string, object>) dictionary), string.Empty, deserializedObject);
return (IValueProvider) new DictionaryValueProvider<object>((IDictionary<string, object>) dictionary, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString((IFormatProvider) CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
if (!string.IsNullOrEmpty(prefix))
return prefix + "." + propertyName;
return propertyName;
}
private class EntryLimitedDictionary
{
private static int _maximumDepth = LargeJsonValueProviderFactory.EntryLimitedDictionary.GetMaximumDepth();
private readonly IDictionary<string, object> _innerDictionary;
private int _itemCount;
public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
{
this._innerDictionary = innerDictionary;
}
public void Add(string key, object value)
{
if (++this._itemCount > LargeJsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
throw new InvalidOperationException("JsonValueProviderFactory_RequestTooLarge");
this._innerDictionary.Add(key, value);
}
private static int GetMaximumDepth()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
if (appSettings != null)
{
string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
int result;
if (values != null && values.Length > 0 && int.TryParse(values[0], out result))
return result;
}
return 1000;
}
}
}
Then, in the Application_Start method from Global.asax.cs, replace the ValueProviderFactory with the new one:
protected void Application_Start()
{
...
//Add LargeJsonValueProviderFactory
ValueProviderFactory jsonFactory = null;
foreach (var factory in ValueProviderFactories.Factories)
{
if (factory.GetType().FullName == "System.Web.Mvc.JsonValueProviderFactory")
{
jsonFactory = factory;
break;
}
}
if (jsonFactory != null)
{
ValueProviderFactories.Factories.Remove(jsonFactory);
}
var largeJsonValueProviderFactory = new LargeJsonValueProviderFactory();
ValueProviderFactories.Factories.Add(largeJsonValueProviderFactory);
}
Go to /xampp/mysql/bin
and find for mysql. exe
open cmd
, change the directory to mysq
after write in cmd
mysql -h localhost -u root
The Object.entries()
method has been specified in ES2017 (and is supported in all modern browsers):
for (const [ key, value ] of Object.entries(dictionary)) {
// do something with `key` and `value`
}
Explanation:
Object.entries()
takes an object like { a: 1, b: 2, c: 3 }
and turns it into an array of key-value pairs: [ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
.
With for ... of
we can loop over the entries of the so created array.
Since we are guaranteed that each of the so iterated array items is itself a two-entry array, we can use destructuring to directly assign variables key
and value
to its first and second item.
That will only work for small numbers and I'm guessing it's also implementation-dependent. Python uses the same object instance for small numbers (iirc <256), but this changes for bigger numbers.
>>> a = 2104214124
>>> b = 2104214124
>>> a == b
True
>>> a is b
False
So you should always use ==
to compare numbers.
Don't post the data as an array. To bind to a list, the key/value pairs should be submitted with the same value for each key.
You should not need a form to do this. You just need a list of key/value pairs, which you can include in the call to $.post.
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
Seems a bit too late, but there is a PPA repository with SmartGit, enjoy! =)
You may also run into problems with certificates from your proxy. There are plenty of answers here on how to retrieve your proxy's certificate.
On a Windows host, to allow pip to clear your proxy, you may want to set an environment variable such as:
PIP_CERT=C:\path\to\certificate\file\in\pem\form\myproxycert.pem
You can also use the --cert
argument to PIP
with the same result.
I have written this article about the ICommand interface.
The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param)
is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param))
.
Requires the method to switching event CanExecuteChanged
. It is called from the user interface elements for switching the state CanExecute()
command.
public class ModelCommand : ICommand
{
#region Constructors
public ModelCommand(Action<object> execute)
: this(execute, null) { }
public ModelCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
Check if the user has scrolled past the header ad, then display the footer ad.
if($(your header ad).position().top < 0) { $(your footer ad).show() }
Am I correct at what you are looking for?
I try lots of ways and finally try this:
def db_persist(func):
def persist(*args, **kwargs):
func(*args, **kwargs)
try:
session.commit()
logger.info("success calling db func: " + func.__name__)
return True
except SQLAlchemyError as e:
logger.error(e.args)
session.rollback()
return False
return persist
and :
@db_persist
def insert_or_update(table_object):
return session.merge(table_object)
you can always use new stdClass()
. Example code:
$object = new stdClass();
$object->property = 'Here we go';
var_dump($object);
/*
outputs:
object(stdClass)#2 (1) {
["property"]=>
string(10) "Here we go"
}
*/
Also as of PHP 5.4 you can get same output with:
$object = (object) ['property' => 'Here we go'];
I think one of the major reasons is locality. Your input file size is 165G, the file's related blocks certainly distributed over multiple DataNodes, more executors can avoid network copy.
Try to set executor num equal blocks count, i think can be faster.
Alternatively you could replace all the contents in your .htaccess file
Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
See the docs here. https://laravel.com/docs/5.8/installation#web-server-configuration
B business day frequency
C custom business day frequency (experimental)
D calendar day frequency
W weekly frequency
M month end frequency
SM semi-month end frequency (15th and end of month)
BM business month end frequency
CBM custom business month end frequency
MS month start frequency
SMS semi-month start frequency (1st and 15th)
BMS business month start frequency
CBMS custom business month start frequency
Q quarter end frequency
BQ business quarter endfrequency
QS quarter start frequency
BQS business quarter start frequency
A year end frequency
BA, BY business year end frequency
AS, YS year start frequency
BAS, BYS business year start frequency
BH business hour frequency
H hourly frequency
T, min minutely frequency
S secondly frequency
L, ms milliseconds
U, us microseconds
N nanoseconds
See the timeseries documentation. It includes a list of offsets (and 'anchored' offsets), and a section about resampling.
Note that there isn't a list of all the different how
options, because it can be any NumPy array function and any function that is available via groupby dispatching can be passed to how
by name.
SIMPLE method may not be the best for all cases
<%
if (Session["Utype"].ToString() == "1")
{
%>
<li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>
<li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
<%
}
else
{
%>
<li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
<%
}
%>
[value]="item" using *ngFor also works with Reactive Forms in Angular 2 and 4
<label *ngFor="let item of items">
<input type="radio" formControlName="options" [value]="item">
{{item}}
</label>`
I did installing watchman, changing limit etc. and it didn't work in Gulp.
Restarting iterm2 actually helped though.
Have a look at iconv()
or mb_convert_encoding()
.
Just by the way: why don't utf8_encode()
and utf8_decode()
work for you?
utf8_decode — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1
utf8_encode — Encodes an ISO-8859-1 string to UTF-8
So essentially
$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded
$iso88591_1 = utf8_decode($utf8);
$iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8);
$iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded
$utf8_1 = utf8_encode($iso88591);
$utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591);
$utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1');
all should do the same - with utf8_en/decode()
requiring no special extension, mb_convert_encoding()
requiring ext/mbstring and iconv()
requiring ext/iconv.
The statement
if A:
will call A.__nonzero__()
(see Special method names documentation) and use the return value of that function. Here's the summary:
object.__nonzero__(self)
Called to implement truth value testing and the built-in operation
bool()
; should returnFalse
orTrue
, or their integer equivalents0
or1
. When this method is not defined,__len__()
is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither__len__()
nor__nonzero__()
, all its instances are considered true.
On the other hand,
if A is not None:
compares only the reference A
with None
to see whether it is the same or not.
In my case, using MAC OS X 10.11 and Android 2.0, and by doing exactly what Aqib Mumtaz has explained.
But, each time, I had this message : "A problem occurred configuring project ':app'. > Cannot evaluate module xxx : Configuration with name 'default' not found."
I found that the reason of this message is that Android 2.0 doesn't allow to create a library directly. So, I have decided first to create an app projet and then to modify the build.gradle in order to transform it as a library.
This solution doesn't work, because a Library project is very different than an app project.
So, I have resolved my problem like this :
Then continue with the solution proposed by Aqib Mumtaz.
As a result, your library source will be shared without needing to duplicate source files each time (it was an heresy for me!)
Hoping that this help you.
Another possibility to make composer think you're using the correct version of PHP is to add to the config
section of a composer.json
file a platform option, like this:
"config": {
"platform": {
"php": "<ver>"
}
},
Where <ver>
is the PHP version of your choice.
Snippet from the docs:
Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: {"php": "7.0.3", "ext-something": "4.0.3"}.
if val % 1 == 0:
val = int(val)
else:
val = float(val)
This worked for me.
How it works: if the remainder of the quotient of val and 1 is 0, val has to be an integer and can, therefore, be declared to be int without having to worry about losing decimal numbers.
Compare these two situations:
A:
val = 12.00
if val % 1 == 0:
val = int(val)
else:
val = float(val)
print(val)
In this scenario, the output is 12, because 12.00 divided by 1 has the remainder of 0. With this information we know, that val doesn't have any decimals and we can declare val to be int.
B:
val = 13.58
if val % 1 == 0:
val = int(val)
else:
val = float(val)
print(val)
This time the output is 13.58, because when val is divided by 1 there is a remainder (0.58) and therefore val is declared to be a float.
By just declaring the number to be an int (without testing the remainder) decimal numbers will be cut off.
This way there are no zeros in the end and no other than the zeros will be ignored.
Unfortunately none of the above solved the problem for me.
I didn't want to edit the bootstrap-responsive.css so I went the easy way:
@media (min-width: 768px) and (max-width: 979px)
(line 461 with latest bootstrap version 2.3.1 as of today)@media (min-width: 979px)
in the place where it said @media (min-width: 768px) and (max-width: 979px)
before. This sets the from 768 to 979 style to everything above 768.That's it. It's not optimal, you will have duplicated css, but it works 100% perfect!
Steps I took to make it work
Restarting the application should work.
Text objects: http://vim.wikia.com/wiki/Creating_new_text_objects
http://vimdoc.sourceforge.net/htmldoc/motion.html#text-objects
In /etc/ansible/ansible.cfg
uncomment the line:
host_key_check = False
and in /etc/ansible/hosts
uncomment the line
client_ansible ansible_ssh_host=10.1.1.1 ansible_ssh_user=root ansible_ssh_pass=12345678
That's all
Get the full width and height of the screen and create a new window set to the appropriate width and height, and with everything disabled. Create a canvas inside of that new window, setting the width and height of the canvas to the width - 10px and the height - 20px (to allow for the bar and the edges of the window). Then work your magic on that canvas.
Using the stat
to figure out the last modification date of the file, date
to figure out the current time and a liberal use of bashisms, one can do the test that you want based on the file's last modification time1.
if [ "$(( $(date +"%s") - $(stat -c "%Y" $somefile) ))" -gt "7200" ]; then
echo "$somefile is older then 2 hours"
fi
While the code is a bit less readable then the find
approach, I think its a better approach then running find
to look at a file you already "found". Also, date manipulation is fun ;-)
%Z
instead of %Y
below to get "change time" which may be what you want.[Update]
For mac users, use stat -f "%m" $somefile
instead of the Linux specific syntax above
How about .delay()
?
$("#test").animate({"top":"-=80px"},1500)
.delay(1000)
.animate({"opacity":"0"},500);
Another way to install python3 is using wget. Below are the steps for installation.
wget http://www.python.org/ftp/python/3.3.5/Python-3.3.5.tar.xz
tar xJf ./Python-3.3.5.tar.xz
cd ./Python-3.3.5
./configure --prefix=/opt/python3.3
make && sudo make install
Also,one can create an alias for the same using
echo 'alias py="/opt/python3.3/bin/python3.3"' >> ~/.bashrc
Now open a new terminal and type py and press Enter.
As "me1" has mentioned you can do this assuming that your version of Windows 7 is either Professional or Ultimate, the PC is on the domain and you have preinstall the Remote Server Administration Tools (Windows6.1-KB958830-x64-RefreshPkg.msu or newer) then you'll be able to do the following:
Step 1. Select "Start", select "Control Panel", select "Programs" and click on "Turn Windows features on or off".
Step 2. Check the following 5 features:
"remote server administration tools>feature administration tools>group policy management tools"
"remote server administration tools>feature administration tools>smtp server tools"
"remote server administration tools>role administration tools>ad ds and ad lds tools>active directory module for windows powershell"
"remote server administration tools>role administration tools>ad ds and ad lds tools>ad ds tools>active directory administrative center"
"remote server administration tools>role administration tools>ad ds and ad lds tools>ad ds tools>ad ds snap-ins and command-line tools"
Step 3. Click "OK".
I had this issue, this is how i have solved it. The problem mostly is that your Angular version is not supporting your Node.js version for the build. So the best solution is to upgrade your Node.js to the most current stable one.
For a clean upgrade of Node.js, i advise using n. if you are using Mac.
npm install -g n
npm cache clean -f
sudo n stable
npm update -g
and now check that you are updated:
node -v
npm -v
For more details, check this link: here
If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch()
. Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.
Other answers generally pointed out the difference between Bash and a POSIX shell standard. However, when writing portable shell scripts and being used to Bash syntax, a list of typical bashisms and corresponding pure POSIX solutions is very handy. Such list has been compiled when Ubuntu switched from Bash to Dash as default system shell and can be found here: https://wiki.ubuntu.com/DashAsBinSh
Moreover, there is a great tool called checkbashisms that checks for bashisms in your script and comes handy when you want to make sure that your script is portable.
If you'd like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,
$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('d-m-Y');
Or, equivalently:
$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');
You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.
Or if the source-format always is "Y-m-d" (yyyy-mm-dd), then just use DateTime:
<?php
$source = '2012-07-31';
$date = new DateTime($source);
echo $date->format('d.m.Y'); // 31.07.2012
echo $date->format('d-m-Y'); // 31-07-2012
?>
First copy the current string to a larger array with strcpy, then use strcat.
For example you can do:
char* str = "Hello";
char dest[12];
strcpy( dest, str );
strcat( dest, ".txt" );
People already mentioned that
Task.Run(A);
Is equivalent to
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
But no one mentioned that
Task.Factory.StartNew(A);
Is equivalent to:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);
As you can see two parameters are different for Task.Run
and Task.Factory.StartNew
:
TaskCreationOptions
- Task.Run
uses TaskCreationOptions.DenyChildAttach
which means that children tasks can not be attached to the parent, consider this:
var parentTask = Task.Run(() =>
{
var childTask = new Task(() =>
{
Thread.Sleep(10000);
Console.WriteLine("Child task finished.");
}, TaskCreationOptions.AttachedToParent);
childTask.Start();
Console.WriteLine("Parent task finished.");
});
parentTask.Wait();
Console.WriteLine("Main thread finished.");
When we invoke parentTask.Wait()
, childTask
will not be awaited, even though we specified TaskCreationOptions.AttachedToParent
for it, this is because TaskCreationOptions.DenyChildAttach
forbids children to attach to it. If you run the same code with Task.Factory.StartNew
instead of Task.Run
, parentTask.Wait()
will wait for childTask
because Task.Factory.StartNew
uses TaskCreationOptions.None
TaskScheduler
- Task.Run
uses TaskScheduler.Default
which means that the default task scheduler (the one that runs tasks on Thread Pool) will always be used to run tasks. Task.Factory.StartNew
on the other hand uses TaskScheduler.Current
which means scheduler of the current thread, it might be TaskScheduler.Default
but not always. In fact when developing Winforms
or WPF
applications it is required to update UI from the current thread, to do this people use TaskScheduler.FromCurrentSynchronizationContext()
task scheduler, if you unintentionally create another long running task inside task that used TaskScheduler.FromCurrentSynchronizationContext()
scheduler the UI will be frozen. A more detailed explanation of this can be found here
So generally if you are not using nested children task and always want your tasks to be executed on Thread Pool it is better to use Task.Run
, unless you have some more complex scenarios.
Try to simply use break statement.
Also you can use the following code as an example:
a = [[0,1,0], [1,0,0], [1,1,1]]
b = [[0,0,0], [0,0,0], [0,0,0]]
def check_matr(matr, expVal):
for row in matr:
if len(set(row)) > 1 or set(row).pop() != expVal:
print 'Wrong'
break# or return
else:
print 'ok'
else:
print 'empty'
check_matr(a, 0)
check_matr(b, 0)
Hmm, looks ugly, seems to work.
static class Async
{
public static Task<IDisposable> Lock(object obj)
{
return TaskEx.Run(() =>
{
var resetEvent = ResetEventFor(obj);
resetEvent.WaitOne();
resetEvent.Reset();
return new ExitDisposable(obj) as IDisposable;
});
}
private static readonly IDictionary<object, WeakReference> ResetEventMap =
new Dictionary<object, WeakReference>();
private static ManualResetEvent ResetEventFor(object @lock)
{
if (!ResetEventMap.ContainsKey(@lock) ||
!ResetEventMap[@lock].IsAlive)
{
ResetEventMap[@lock] =
new WeakReference(new ManualResetEvent(true));
}
return ResetEventMap[@lock].Target as ManualResetEvent;
}
private static void CleanUp()
{
ResetEventMap.Where(kv => !kv.Value.IsAlive)
.ToList()
.ForEach(kv => ResetEventMap.Remove(kv));
}
private class ExitDisposable : IDisposable
{
private readonly object _lock;
public ExitDisposable(object @lock)
{
_lock = @lock;
}
public void Dispose()
{
ResetEventFor(_lock).Set();
}
~ExitDisposable()
{
CleanUp();
}
}
}
A nice web based tool is ungit. It runs on any platform that node.js & git supports. There is a video of how it works for those that find that sort of things easier than reading...
in my case, some characters like " , :"'{}[] " maybe corrupt the JSON format, so use try json.loads(str) except to check your input
you missed jquery ui library. Use CDN of Jquery UI or if you want it locally then download the file from Jquery Ui
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src="YourJquery source path"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>
First create a class to represent your json data.
public class MyFlightDto
{
public string err_code { get; set; }
public string org { get; set; }
public string flight_date { get; set; }
// Fill the missing properties for your data
}
Using Newtonsoft JSON serializer to Deserialize a json string to it's corresponding class object.
var jsonInput = "{ org:'myOrg',des:'hello'}";
MyFlightDto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<MyFlightDto>(jsonInput);
Or Use JavaScriptSerializer
to convert it to a class(not recommended as the newtonsoft json serializer seems to perform better).
string jsonInput="have your valid json input here"; //
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Customer objCustomer = jsonSerializer.Deserialize<Customer >(jsonInput)
Assuming you want to convert it to a Customer
classe's instance. Your class should looks similar to the JSON
structure (Properties)
Please check the below code :
/*Get current URL*/
var _url = location.href;
/*Check if the url already contains ?, if yes append the parameter, else add the parameter*/
_url = ( _url.indexOf('?') !== -1 ) ? _url+'¶m='+value : _url+'?param='+value;
/*reload the page */
window.location.href = _url;
You should use the ISO-8601 format for string representations of dates - anything else is dependent on the SQL Server language and dateformat settings.
The ISO-8601 format for a DATETIME
when using only the date is: YYYYMMDD
(no dashes or antyhing!)
For a DATETIME
with the time portion, it's YYYY-MM-DDTHH:MM:SS
(with dashes, and a T
in the middle to separate date and time portions).
If you want to convert a string to a DATE
for SQL Server 2008 or newer, you can use YYYY-MM-DD
(with the dashes) to achieve the same result. And don't ask me why this is so inconsistent and confusing - it just is, and you'll have to work with that for now.
So in your case, you should try:
declare @a datetime
declare @b datetime
set @a = '2012-04-06T12:23:45' -- 6th of April, 2012
set @b = '2012-08-06T21:10:12' -- 6th of August, 2012
exec LogProcedure 'AccountLog', N'test', @a, @b
Furthermore - your stored proc has problem, since you're concatenating together datetime
and string into a string, but you're not converting the datetime
to string first, and also, you're forgetting the close quotes in your statement after both dates.
So change this line here to this:
IF @DateFirst <> '' and @DateLast <> ''
SET @FinalSQL = @FinalSQL + ' OR CONVERT(Date, DateLog) >= ''' +
CONVERT(VARCHAR(50), @DateFirst, 126) + -- convert @DateFirst to string for concatenation!
''' AND CONVERT(Date, DateLog) <=''' + -- you need closing quotes after @DateFirst!
CONVERT(VARCHAR(50), @DateLast, 126) + '''' -- convert @DateLast to string and also: closing tags after that missing!
With these settings, and once you've fixed your stored procedure which contains problems right now, it will work.
When I tested this, I tried using the position property and it worked perfectly.
HTML
<div class="main">
<div class="body">
//add content here
</body>
</div>
CSS
.main{
position: relative;
}
.body{
position: absolute;
height: 100%;
}
I think this could work:
select * from tbl where statusid = isnull(@statusid,statusid)
SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).
(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).
You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.
It's embedded in a standard XML comment, and looks like this:
<!--#include virtual="top.shtml" -->
It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.
You can read more in this Wikipedia article.
(new FileInfo(filePath)).Directory.Create()
Before writing to the file.
System.IO.FileInfo file = new System.IO.FileInfo(filePath);
file.Directory.Create(); // If the directory already exists, this method does nothing.
System.IO.File.WriteAllText(file.FullName, content);
Just throwing this out there...Can't you just do:
Collections.sort(myarrayList);
It's been awhile though...
The other solutions are good. If these are your goals:
These two lines are useful ...
df.persist
df.show(df.count, false) // in Scala or 'False' in Python
By persisting, the 2 executor actions, count and show, are faster & more efficient when using persist
or cache
to maintain the interim underlying dataframe structure within the executors. See more about persist and cache.
// from http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
If you want dot/comma separated numbers also, then:
\d*\.?\d*
or
[0-9]*\.?[0-9]*
You can use https://regex101.com/ to test your regexes.
I think that you'll find interesting stuff in the following answer of mine that I did for a previous similar question:
https://stackoverflow.com/q/5929469/551449
In this answer, I proposed a pattern that allows a regex to catch any kind of number and since I have nothing else to add to it, I think it is fairly complete
After reading through different methods suggested in the above answers, I decided to handle the authentication exceptions by using a custom filter. I was able to handle the response status and codes using an error response class using the following method.
I created a custom filter and modified my security config by using the addFilterAfter method and added after the CorsFilter class.
@Component
public class AuthFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//Cast the servlet request and response to HttpServletRequest and HttpServletResponse
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// Grab the exception from the request attribute
Exception exception = (Exception) request.getAttribute("javax.servlet.error.exception");
//Set response content type to application/json
httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
//check if exception is not null and determine the instance of the exception to further manipulate the status codes and messages of your exception
if(exception!=null && exception instanceof AuthorizationParameterNotFoundException){
ErrorResponse errorResponse = new ErrorResponse(exception.getMessage(),"Authetication Failed!");
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = httpServletResponse.getWriter();
writer.write(convertObjectToJson(errorResponse));
writer.flush();
return;
}
// If exception instance cannot be determined, then throw a nice exception and desired response code.
else if(exception!=null){
ErrorResponse errorResponse = new ErrorResponse(exception.getMessage(),"Authetication Failed!");
PrintWriter writer = httpServletResponse.getWriter();
writer.write(convertObjectToJson(errorResponse));
writer.flush();
return;
}
else {
// proceed with the initial request if no exception is thrown.
chain.doFilter(httpServletRequest,httpServletResponse);
}
}
public String convertObjectToJson(Object object) throws JsonProcessingException {
if (object == null) {
return null;
}
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
}
SecurityConfig class
@Configuration
public class JwtSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
AuthFilter authenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(authenticationFilter, CorsFilter.class).csrf().disable()
.cors(); //........
return http;
}
}
ErrorResponse class
public class ErrorResponse {
private final String message;
private final String description;
public ErrorResponse(String description, String message) {
this.message = message;
this.description = description;
}
public String getMessage() {
return message;
}
public String getDescription() {
return description;
}}