As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker
JS:
$scope.setSelected = function(selected) {
$scope.selected = selected;
}
HTML:
{{ selected }}
<ul>
<li ng-class="{current: selected == 100}">
<a href ng:click="setSelected(100)">ABC</a>
</li>
<li ng-class="{current: selected == 101}">
<a href ng:click="setSelected(101)">DEF</a>
</li>
<li ng-class="{current: selected == $index }"
ng-repeat="x in [4,5,6,7]">
<a href ng:click="setSelected($index)">A{{$index}}</a>
</li>
</ul>
<div
ng:show="selected == 100">
100
</div>
<div
ng:show="selected == 101">
101
</div>
<div ng-repeat="x in [4,5,6,7]"
ng:show="selected == $index">
{{ $index }}
</div>
There are two ways to hide video tag controls
Remove the controls
attribute from the video tag.
Add the css to the video tag
video::-webkit-media-controls-panel {
display: none !important;
opacity: 1 !important;}
While you could try these settings in config file
<system.web>
<httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
<pages validateRequest="false" />
</system.web>
I would avoid using characters like '&' in URL path replacing them with underscores.
:
is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]
[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"
Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.
Works with tuples and strings, too.
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
There is an illustrative example of how to create custom colormaps here.
The docstring is essential for understanding the meaning of
cdict
. Once you get that under your belt, you might use a cdict
like this:
cdict = {'red': ((0.0, 1.0, 1.0),
(0.1, 1.0, 1.0), # red
(0.4, 1.0, 1.0), # violet
(1.0, 0.0, 0.0)), # blue
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 0.0),
(0.1, 0.0, 0.0), # red
(0.4, 1.0, 1.0), # violet
(1.0, 1.0, 0.0)) # blue
}
Although the cdict
format gives you a lot of flexibility, I find for simple
gradients its format is rather unintuitive. Here is a utility function to help
generate simple LinearSegmentedColormaps:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def make_colormap(seq):
"""Return a LinearSegmentedColormap
seq: a sequence of floats and RGB-tuples. The floats should be increasing
and in the interval (0,1).
"""
seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
cdict = {'red': [], 'green': [], 'blue': []}
for i, item in enumerate(seq):
if isinstance(item, float):
r1, g1, b1 = seq[i - 1]
r2, g2, b2 = seq[i + 1]
cdict['red'].append([item, r1, r2])
cdict['green'].append([item, g1, g2])
cdict['blue'].append([item, b1, b2])
return mcolors.LinearSegmentedColormap('CustomMap', cdict)
c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
[c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()
By the way, the for-loop
for i in range(0, len(array_dg)):
plt.plot(array_dg[i], markers.next(),alpha=alpha[i], c=colors.next())
plots one point for every call to plt.plot
. This will work for a small number of points, but will become extremely slow for many points. plt.plot
can only draw in one color, but plt.scatter
can assign a different color to each dot. Thus, plt.scatter
is the way to go.
On a Mac, you can do this to copy it to your clipboard (like cmd + c
shortcut)
cat ~/Desktop/ded.html | pbcopy
pbcopy < ~/.ssh/id_rsa.pub
and to paste
pbpaste > ~Documents/id_rsa.txt
or, use cmd + v
shorcut
to paste it somewhere else.
~/.ssh
is the same path as /Users/macbook-username/.ssh
You can use Print work directory: pwd
command on terminal to get the path to your current directory.
Could write a udf and take a value to tell it which day of the week should be 1 would look like this (drawing on answer from John to use MOD instead of CASE):
DROP FUNCTION IF EXISTS `reporting`.`udfDayOfWeek`;
DELIMITER |
CREATE FUNCTION `reporting`.`udfDayOfWeek` (
_date DATETIME,
_firstDay TINYINT
) RETURNS tinyint(4)
FUNCTION_BLOCK: BEGIN
DECLARE _dayOfWeek, _offset TINYINT;
SET _offset = 8 - _firstDay;
SET _dayOfWeek = (DAYOFWEEK(_date) + _offset) MOD 7;
IF _dayOfWeek = 0 THEN
SET _dayOfWeek = 7;
END IF;
RETURN _dayOfWeek;
END FUNCTION_BLOCK
To call this function to give you the current day of week value when your week starts on a Tuesday for instance, you'd call:
SELECT udfDayOfWeek(NOW(), 3);
Nice thing about having it as a udf is you could also call it on a result set field like this:
SELECT
udfDayOfWeek(p.SignupDate, 3) AS SignupDayOfWeek,
p.FirstName,
p.LastName
FROM Profile p;
"F:\- Big Packets -\kitterengine\Common\Template.bat"
maybe prefaced with call
(see call /?
). Or Cd /d "F:\- Big Packets -\kitterengine\Common\" & Template.bat
.
CMD Cheat Sheet
Cmd.exe
Getting Help
Punctuation
Naming Files
Starting Programs
Keys
CMD.exe
First thing to remember its a way of operating a computer. It's the way we did it before WIMP (Windows, Icons, Mouse, Popup menus) became common. It owes it roots to CPM, VMS, and Unix. It was used to start programs and copy and delete files. Also you could change the time and date.
For help on starting CMD type cmd /?
. You must start it with either the /k
or /c
switch unless you just want to type in it.
Getting Help
For general help. Type Help
in the command prompt. For each command listed type help <command>
(eg help dir
) or <command> /?
(eg dir /?
).
Some commands have sub commands. For example schtasks /create /?
.
The NET
command's help is unusual. Typing net use /?
is brief help. Type net help use
for full help. The same applies at the root - net /?
is also brief help, use net help
.
References in Help to new behaviour are describing changes from CMD in OS/2 and Windows NT4 to the current CMD which is in Windows 2000 and later.
WMIC
is a multipurpose command. Type wmic /?
.
Punctuation
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's
errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
2> Redirects command error output to the file specified. (0 is StdInput, 1 is StdOutput, and 2 is StdError)
2>&1 Redirects command error output to the same location as command output.
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed
to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatenate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files
modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution
time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0
is the batchfile's name.
%* (%*) the entire command line.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor (from set /?).
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop.
Single % sign at command prompt and double % sign in a batch file.
\\ (\\servername\sharename\folder\file.ext) access files and folders via UNC naming.
: (win.ini:streamname) accesses an alternative steam. Also separates drive from rest of path.
. (win.ini) the LAST dot in a file path separates the name from extension
. (dir .\*.txt) the current directory
.. (cd ..) the parent directory
\\?\ (\\?\c:\windows\win.ini) When a file path is prefixed with \\?\ filename checks are turned off.
Naming Files
< > : " / \ | Reserved characters. May not be used in filenames.
Reserved names. These refer to devices eg,
copy filename con
which copies a file to the console window.
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4,
COM5, COM6, COM7, COM8, COM9, LPT1, LPT2,
LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9
CONIN$, CONOUT$, CONERR$
--------------------------------
Maximum path length 260 characters
Maximum path length (\\?\) 32,767 characters (approx - some rare characters use 2 characters of storage)
Maximum filename length 255 characters
Starting a Program
See start /?
and call /?
for help on all three ways.
There are two types of Windows programs - console or non console (these are called GUI even if they don't have one). Console programs attach to the current console or Windows creates a new console. GUI programs have to explicitly create their own windows.
If a full path isn't given then Windows looks in
The directory from which the application loaded.
The current directory for the parent process.
Windows NT/2000/XP: The 32-bit Windows system directory. Use the GetSystemDirectory function to get the path of this directory. The name of this directory is System32.
Windows NT/2000/XP: The 16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System.
The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
The directories that are listed in the PATH environment variable.
Specify a program name
This is the standard way to start a program.
c:\windows\notepad.exe
In a batch file the batch will wait for the program to exit. When typed the command prompt does not wait for graphical programs to exit.
If the program is a batch file control is transferred and the rest of the calling batch file is not executed.
Use Start command
Start
starts programs in non standard ways.
start "" c:\windows\notepad.exe
Start
starts a program and does not wait. Console programs start in a new window. Using the /b
switch forces console programs into the same window, which negates the main purpose of Start.
Start uses the Windows graphical shell - same as typing in WinKey + R (Run dialog). Try
start shell:cache
Also program names registered under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
can also be typed without specifying a full path.
Also note the first set of quotes, if any, MUST be the window title.
Use Call command
Call is used to start batch files and wait for them to exit and continue the current batch file.
Other Filenames
Typing a non program filename is the same as double clicking the file.
Keys
Ctrl + C exits a program without exiting the console window.
For other editing keys type Doskey /?
.
? and ? recall commands
ESC clears command line
F7 displays command history
ALT+F7 clears command history
F8 searches command history
F9 selects a command by number
ALT+F10 clears macro definitions
Also not listed
Ctrl + ?or? Moves a word at a time
Ctrl + Backspace Deletes the previous word
Home Beginning of line
End End of line
Ctrl + End Deletes to end of line
See in the android sdk directory.
In \platforms\android-X\data\res\values\themes.xml
:
<item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
<item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
<item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>
In \platforms\android-X\data\res\values\styles.xml
:
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
</style>
<style name="TextAppearance.Medium">
<item name="android:textSize">18sp</item>
</style>
<style name="TextAppearance.Small">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?textColorSecondary</item>
</style>
TextAppearance.Large
means style is inheriting from TextAppearance
style, you have to trace it also if you want to see full definition of a style.
Link: http://developer.android.com/design/style/typography.html
setInterval(function() {
updatechat();
}, 2000);
function updatechat() {
alert('hello world');
}
I have encountered the same problem several times. After enabling less secure app option the problem resolved. Enable less secure app from here: https://myaccount.google.com/lesssecureapps
hope this will help.
ServicePointManager.ServerCertificateValidationCallback +=
(mender, certificate, chain, sslPolicyErrors) => true;
will bypass invaild ssl . Write it to your web service constructor.
You are testing if the values of the variables error
and Already
are present in RepoOutput[RepoName.index(repo)]
. If these variables don't exist then an undefined object is used.
Both of your if
and elif
tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].
I think you wanted to test if certain strings are in the value instead:
{% if "error" in RepoOutput[RepoName.index(repo)] %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
<td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
<td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>
Other corrections I made:
{% elif ... %}
instead of {$ elif ... %}
.</tr>
tag out of the if
conditional structure, it needs to be there always.id
attributeNote that most likely you want to use a class
attribute instead here, not an id
, the latter must have a value that must be unique across your HTML document.
Personally, I'd set the class value here and reduce the duplication a little:
{% if "Already" in RepoOutput[RepoName.index(repo)] %}
{% set row_class = "good" %}
{% else %}
{% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>
People have recommended MailChimp which is a good vendor for bulk email. If you're looking for a good vendor for transactional email, I might be able to help.
Over the past 6 months, we used four different SMTP vendors with the goal of figuring out which was the best one.
Here's a summary of what we found...
Conclusion
SendGrid was the best with Postmark coming in second place. We never saw any hesitation in send times with either of those two - in some cases we sent several hundred emails at once - and they both have the best ROI, given a solid featureset.
No - the object approach is JavaScript's answer to this. There is no problem with this provided your function expects an object rather than separate params.
You can use this function, which creates a tempfile in the filesystem and returns the path to the downloaded file if everything worked fine:
function getFileContents($url)
{
// Workaround: Save temp file
$img = tempnam(sys_get_temp_dir(), 'pdf-');
$img .= '.' . pathinfo($url, PATHINFO_EXTENSION);
$fp = fopen($img, 'w+');
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);
return $result ? $img : false;
}
Simple and best code:
def max_occ(lst,x):
count=0
for i in lst:
if (i==x):
count=count+1
return count
lst=[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
x=max(lst,key=lst.count)
print(x,"occurs ",max_occ(lst,x),"times")
Output: 4 occurs 6 times
As others already answered, $nbsp;
will output no-break space character.
Here is w3 docs for  
and others.
However there is other ways to do it and nowdays i would prefer using CSS stylesheets. There is also w3c tutorials for beginners.
With CSS you can do it like this:
<html>
<head>
<title>CSS test</title>
<style type="text/css">
p { word-spacing: 40px; }
</style>
</head>
<body>
<p>Hello World! Enough space between words, what do you think about it?</p>
</body>
</html>
firstly you have to change the drive, which is allocated to your usb.
follow these step to access your pendrive using CMD. 1- type drivename follow by the colon just like k: 2- type dir it will show all the files and directory in your usb 3- now you can access any file or directory of your usb.
I always return multiple values by using a combination of list()
and array()
s:
function DecideStuffToReturn() {
$IsValid = true;
$AnswerToLife = 42;
// Build the return array.
return array($IsValid, $AnswerToLife);
}
// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();
You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.
See list()
for more information.
If you're using QT Creator 5.6 you can do that like this:
#include <QIntValidator>
ui->myLineEditName->setValidator( new QIntValidator);
I recomend you put that line after ui->setupUi(this);
I hope this helps.
You will have to provide a link to your file that is accessible through the browser, that is for instance:
<a href="http://my.domain.com/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
versus
<a href="C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
If you expose your "Projecten" folder directly to the public, then you may only have to provide the link as such:
<a href="/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
But beware, that your files can then be indexed by search engines, can be accessed by anybody having this link, etc.
I used ImportIO. They let you request the HTML from any website if you set up an account with them (which is free). They let you make up to 50k requests per year. I didn't take them time to find an alternative, but I'm sure there are some.
In your Javascript, you'll basically just make a GET request like this:
var request = new XMLHttpRequest();_x000D_
_x000D_
request.onreadystatechange = function() {_x000D_
jsontext = request.responseText;_x000D_
_x000D_
alert(jsontext);_x000D_
}_x000D_
_x000D_
request.open("GET", "https://extraction.import.io/query/extractor/THE_PUBLIC_LINK_THEY_GIVE_YOU?_apikey=YOUR_KEY&url=YOUR_URL", true);_x000D_
_x000D_
request.send();
_x000D_
Sidenote: I found this question while researching what I felt like was the same question, so others might find my solution helpful.
UPDATE: I created a new one which they just allowed me to use for less than 48 hours before they said I had to pay for the service. It seems that they shut down your project pretty quick now if you aren't paying. I made my own similar service with NodeJS and a library called NightmareJS. You can see their tutorial here and create your own web scraping tool. It's relatively easy. I haven't tried to set it up as an API that I could make requests to or anything.
This my implementation which you can providing in application scope:
class NetworkStateHelper @Inject constructor(
private val context: Context
) {
private val cache: BehaviorSubject<Boolean> = BehaviorSubject.create()
private val receiver = object : BroadcastReceiver() {
override fun onReceive(c: Context?, intent: Intent?) {
cache.onNext(isOnlineOrConnecting())
}
}
init {
val intentFilter = IntentFilter()
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
context.registerReceiver(receiver, intentFilter)
cache.onNext(isOnlineOrConnecting())
}
fun subscribe(): Observable<Boolean> {
return cache
}
fun isOnlineOrConnecting(): Boolean {
val cm = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val netInfo = cm.activeNetworkInfo
return netInfo != null && netInfo.isConnectedOrConnecting
}
}
I used this rxjava and dagger2 libraies
The u- prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. Don't be thrown by the printed output.
For example, try this:
print mail_accounts[0]["i"]
You won't see a u.
Another portable solution:
POSH: The Portable Open Source Harness
"POSH is a simple, portable, easy-to-use, easy-to-integrate, flexible, open source "harness" designed to make writing cross-platform libraries and applications significantly less tedious to create and port."
http://poshlib.hookatooka.com/poshlib/trac.cgi
as described and used in the book: Write portable code: an introduction to developing software for multiple platforms By Brian Hook http://books.google.ca/books?id=4VOKcEAPPO0C
-Jason
You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:
<div class="container">
<div class="row">
<div class="col-sm-4 col-md-4 col-lg-4">
<div class="centerBlock">
<img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
</div>
</div>
<div class="col-sm-8 col-md-8 col-lg-8">
Some content not important at this moment
</div>
</div>
</div>
// CSS
.centerBlock {
display: table;
margin: auto;
}
This page comes first when you search on Google "remove last character jquery"
Although all previous answers are correct, somehow did not helped me to find what I wanted in a quick and easy way.
I feel something is missing. Apologies if i'm duplicating
jQuery
$('selector').each(function(){
var text = $(this).html();
text = text.substring(0, text.length-1);
$(this).html(text);
});
or
$('selector').each(function(){
var text = $(this).html();
text = text.slice(0,-1);
$(this).html(text);
})
A simple answer for rgb to hex
function rgbtohex(r,g,b){
return "#" + (Math.round(r) * 65536 + Math.round(g) * 256 + Math.round(b)).toString(16));
}
As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.
Hibernate itself admits that its connection pooling strategy is minimal
Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
I personally use C3P0
. however there are other alternatives available including DBCP
.
Check out
Below is a minimal configuration of C3P0 used in my application:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">1800</property> <!-- seconds -->
By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size
Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier.
The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:
Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)
# c3p0.properties
c3p0.testConnectionOnCheckout=true
With this configuration each connection is tested before being used. It however might affect the performance of the site.
The first thing that comes to my mind is a one-liner regex:
var pageNum = $("#specificLink").attr("href").match(/page=([0-9]+)/)[1];
To increase the phpMyAdmin
Session Timeout, open config.inc.php
in the root phpMyAdmin
directory and add this setting (anywhere).
$cfg['LoginCookieValidity'] = <your_new_timeout>;
Where <your_new_timeout>
is some number larger than 1800.
Note:
Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
You could do it like:
Person.where("name = ? OR age = ?", 'Pearl', 24)
or more elegant, install rails_or gem and do it like:
Person.where(:name => 'Pearl').or(:age => 24)
args
contains the command-line arguments passed to the Java program upon invocation. For example, if I invoke the program like so:
$ java MyProg -f file.txt
Then args
will be an array containing the strings "-f"
and "file.txt"
.
Here's the solution I use. I can't remember why I couldn't just use the PictureBox.Load methods. I'm pretty sure it's because I wanted to properly scale & center the downloaded image into the PictureBox control. If I recall, all the scaling options on PictureBox either stretch the image, or will resize the PictureBox to fit the image. I wanted a properly scaled and centered image in the size I set for PictureBox.
Now, I just need to make a async version...
Here's my methods:
#region Image Utilities
/// <summary>
/// Loads an image from a URL into a Bitmap object.
/// Currently as written if there is an error during downloading of the image, no exception is thrown.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static Bitmap LoadPicture(string url)
{
System.Net.HttpWebRequest wreq;
System.Net.HttpWebResponse wresp;
Stream mystream;
Bitmap bmp;
bmp = null;
mystream = null;
wresp = null;
try
{
wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
wreq.AllowWriteStreamBuffering = true;
wresp = (System.Net.HttpWebResponse)wreq.GetResponse();
if ((mystream = wresp.GetResponseStream()) != null)
bmp = new Bitmap(mystream);
}
catch
{
// Do nothing...
}
finally
{
if (mystream != null)
mystream.Close();
if (wresp != null)
wresp.Close();
}
return (bmp);
}
/// <summary>
/// Takes in an image, scales it maintaining the proper aspect ratio of the image such it fits in the PictureBox's canvas size and loads the image into picture box.
/// Has an optional param to center the image in the picture box if it's smaller then canvas size.
/// </summary>
/// <param name="image">The Image you want to load, see LoadPicture</param>
/// <param name="canvas">The canvas you want the picture to load into</param>
/// <param name="centerImage"></param>
/// <returns></returns>
public static Image ResizeImage(Image image, PictureBox canvas, bool centerImage )
{
if (image == null || canvas == null)
{
return null;
}
int canvasWidth = canvas.Size.Width;
int canvasHeight = canvas.Size.Height;
int originalWidth = image.Size.Width;
int originalHeight = image.Size.Height;
System.Drawing.Image thumbnail =
new Bitmap(canvasWidth, canvasHeight); // changed parm names
System.Drawing.Graphics graphic =
System.Drawing.Graphics.FromImage(thumbnail);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
/* ------------------ new code --------------- */
// Figure out the ratio
double ratioX = (double)canvasWidth / (double)originalWidth;
double ratioY = (double)canvasHeight / (double)originalHeight;
double ratio = ratioX < ratioY ? ratioX : ratioY; // use whichever multiplier is smaller
// now we can get the new height and width
int newHeight = Convert.ToInt32(originalHeight * ratio);
int newWidth = Convert.ToInt32(originalWidth * ratio);
// Now calculate the X,Y position of the upper-left corner
// (one of these will always be zero)
int posX = Convert.ToInt32((canvasWidth - (image.Width * ratio)) / 2);
int posY = Convert.ToInt32((canvasHeight - (image.Height * ratio)) / 2);
if (!centerImage)
{
posX = 0;
posY = 0;
}
graphic.Clear(Color.White); // white padding
graphic.DrawImage(image, posX, posY, newWidth, newHeight);
/* ------------- end new code ---------------- */
System.Drawing.Imaging.ImageCodecInfo[] info =
ImageCodecInfo.GetImageEncoders();
EncoderParameters encoderParameters;
encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,
100L);
Stream s = new System.IO.MemoryStream();
thumbnail.Save(s, info[1],
encoderParameters);
return Image.FromStream(s);
}
#endregion
Here's the required includes. (Some might be needed by other code, but including all to be safe)
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using System.Text.RegularExpressions;
using System.Drawing;
How I generally use it:
ImageUtil.ResizeImage(ImageUtil.LoadPicture( "http://someurl/img.jpg", pictureBox1, true);
if you want to look for a div that has more than 1 class try this:
Html:
<div class="class1 class2 class3" id="myDiv">
Jquery:
var check = $( "#myDiv" ).hasClass( "class2" ).toString();
ouput:
true
Have you tried adding the verbose (-v
) operator when you clone?
git clone -v git://git.kernel.org/pub/scm/.../linux-2.6 my2.6
I had a similar issue to this. I solved it by making all the projects within my solution target the same .NET Framework 4 Client Profile and then rebuilding the entire solution.
Since Android Studio 3.2 and Android Emulator 27.3.8 - the android emulator is supported by Windows Hypervisor Platform and as stated in the official android developer blog - there is mac support (since OS X v10.10 Yosemite) and windows support (since April 2018 Update). You may find further instructions on the developer blog.
In my opinion, the performance is significantly better than all previous workarounds.
All those answers are good, but I'd like to add a note on constructors with a little more complex initializations.
class SomeClass {
private int StringLength;
SomeClass(string x) {
// this is the logic that shall be executed for all constructors.
// you dont want to duplicate it.
StringLength = x.Length;
}
SomeClass(int a, int b): this(TransformToString(a, b)) {
}
private static string TransformToString(int a, int b) {
var c = a + b;
return $"{a} + {b} = {c}";
}
}
Allthogh this example might as well be solved without this static function, the static function allows for more complex logic, or even calling methods from somewhere else.
If I remember from your previous questions, you're binding to a DataTable. Try this:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable sourceData = (DataTable)GridView1.DataSource;
sourceData.Rows[e.RowIndex].Delete();
GridVie1.DataSource = sourceData;
GridView1.DataBind();
}
Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.
In XP, the .mru.dat file is in C:\Documents and Settings\Name\Application Data\Microsoft\Microsoft SQL Server\90\Tools\ShellSEM
However, removing it won't do anything.
To remove the list in XP, cut the sqlstudio bin file from C:\Documents and Settings\Name\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell and paste it on your desktop.
Try SQL
If it has worked, then delete the sqlstudio bin file from desktop.
Easy :)
This worked for me:
input[type='number'] {
appearance: none;
}
Solved in Firefox, Safari, Chrome. Also, -moz-appearance: textfield;
is not supported anymore (https://developer.mozilla.org/en-US/docs/Web/CSS/appearance)
There are three way to do it.
var num = 123;
alert(num.toString().length);
better performance one (best performance in ie11)
var num = 123;
alert((num + '').length);
Math (best performance in Chrome, firefox but slowest in ie11)
var num = 123
alert(Math.floor( Math.log(num) / Math.LN10 ) + 1)
there is a jspref here http://jsperf.com/fastest-way-to-get-the-first-in-a-number/2
Set the XML as:
<ToggleButton
android:id="@+id/flashlightButton"
style="@style/Button"
android:layout_above="@+id/buttonStrobeLight"
android:layout_marginBottom="20dp"
android:onClick="onToggleClicked"
android:text="ToggleButton"
android:textOn="Light ON"
android:textOff="Light OFF" />
In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service
to https://my-service
helped.
If anyone looking with time and timezone, this is for you
{{data.ct | date :'dd-MMM-yy h:mm:ss a '}}
add z for time zone at the end of date and time format
{{data.ct | date :'dd-MMM-yy h:mm:ss a z'}}
Or, if you're kicking it old school:
cd /path/to/other/repository
patch -p1 < 0001-whatever.patch
There are a least these apt-get
extension packages that can help:
apt-offline - offline apt package manager
apt-zip - Update a non-networked computer using apt and removable media
This is specifically for the case of wanting to download where you have network access but to install on another machine where you do not.
Otherwise, the --download-only
option to apt-get
is your friend:
-d, --download-only
Download only; package files are only retrieved, not unpacked or installed.
Configuration Item: APT::Get::Download-Only.
$("button").click(function(){_x000D_
alert($("li").length);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>_x000D_
<meta charset="utf-8">_x000D_
<title>Count the number of specific elements</title>_x000D_
</head>_x000D_
<body>_x000D_
<ul>_x000D_
<li>List - 1</li>_x000D_
<li>List - 2</li>_x000D_
<li>List - 3</li>_x000D_
</ul>_x000D_
<button>Display the number of li elements</button>_x000D_
</body>_x000D_
</html>
_x000D_
My mistake, the resource files WERE actually copied to target/test-classes
. The problem seemed to be due to spaces in my project name, e.g. Project%20Name
.
I'm now loading the file as follows and it works:
org.apache.commons.io.FileUtils.toFile(myClass().getResource("resourceFile.txt")??);
Or, (taken from Java: how to get a File from an escaped URL?) this may be better (no dependency on Apache Commons):
myClass().getResource("resourceFile.txt")??.toURI();
You also could use simpler regex designed for your case like (.*)\/(([^\?\n\r])*)
where $2
match what you want.
I often fix that problem with calc()
. You just give the textarea a width of 100% and a certain amount of padding, but you have to subtract the total left and right padding of the 100% width you have given to the textarea:
textarea {
border: 0px;
width: calc(100% -10px);
padding: 5px;
}
Or if you want to give the textarea a border:
textarea {
border: 1px;
width: calc(100% -12px); /* plus the total left and right border */
padding: 5px;
}
There's still no simple answer. It depends on your scenario. MSDN has documentation to help you decide.
There are other options covered here. Instead of storing in the file system directly or in a BLOB, you can use the FileStream or File Table in SQL Server 2012. The advantages to File Table seem like a no-brainier (but admittedly I have no personal first-hand experience with them.)
The article is definitely worth a read.
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
INSERT INTO table1 (col1, col2, col3)
SELECT column1, column2, column3
FROM table2
From the spring docs
Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.
The <context-param>
:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
You can then use the WebApplicationContext to get a handle on your beans.
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");
See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info
Use update_column
(Rails >= v3.1) or update_columns
(Rails >= 4.0) to skip callbacks and validations. Also with these methods, updated_at
is not updated.
#Rails >= v3.1 only
@person.update_column(:some_attribute, 'value')
#Rails >= v4.0 only
@person.update_columns(attributes)
http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_column
#2: Skipping callbacks that also works while creating an object
class Person < ActiveRecord::Base
attr_accessor :skip_some_callbacks
before_validation :do_something
after_validation :do_something_else
skip_callback :validation, :before, :do_something, if: :skip_some_callbacks
skip_callback :validation, :after, :do_something_else, if: :skip_some_callbacks
end
person = Person.new(person_params)
person.skip_some_callbacks = true
person.save
UPDATE (2020)
Apparently Rails has always supported :if
and :unless
options, so above code can be simplified as:
class Person < ActiveRecord::Base
attr_accessor :skip_some_callbacks
before_validation :do_something, unless: :skip_some_callbacks
after_validation :do_something_else, unless: :skip_some_callbacks
end
person = Person.new(person_params)
person.skip_some_callbacks = true
person.save
SELECT (SELECT COALESCE(SUM(London), 0) FROM CASH) + (SELECT COALESCE(SUM(London), 0) FROM CHEQUE) as result
'And so on and so forth.
"The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios." Source
Some time in a single application this Issue also come In that case select these checkbox when you publish your application
Invalid login/password could be also related to issues in your DNS server - that's what happened to me and cost me good 5 hours of my life. See if you can specify ip address instead on domain name.
In addition to what visitor said :
The function void emplace_back(Type&& _Val)
provided by MSCV10 is non conforming and redundant, because as you noted it is strictly equivalent to push_back(Type&& _Val)
.
But the real C++0x form of emplace_back
is really useful: void emplace_back(Args&&...)
;
Instead of taking a value_type
it takes a variadic list of arguments, so that means that you can now perfectly forward the arguments and construct directly an object into a container without a temporary at all.
That's useful because no matter how much cleverness RVO and move semantic bring to the table there is still complicated cases where a push_back is likely to make unnecessary copies (or move). For example, with the traditional insert()
function of a std::map
, you have to create a temporary, which will then be copied into a std::pair<Key, Value>
, which will then be copied into the map :
std::map<int, Complicated> m;
int anInt = 4;
double aDouble = 5.0;
std::string aString = "C++";
// cross your finger so that the optimizer is really good
m.insert(std::make_pair(4, Complicated(anInt, aDouble, aString)));
// should be easier for the optimizer
m.emplace(4, anInt, aDouble, aString);
So why didn't they implement the right version of emplace_back in MSVC? Actually, it bugged me too a while ago, so I asked the same question on the Visual C++ blog. Here is the answer from Stephan T Lavavej, the official maintainer of the Visual C++ standard library implementation at Microsoft.
Q: Are beta 2 emplace functions just some kind of placeholder right now?
A: As you may know, variadic templates aren't implemented in VC10. We simulate them with preprocessor machinery for things like
make_shared<T>()
, tuple, and the new things in<functional>
. This preprocessor machinery is relatively difficult to use and maintain. Also, it significantly affects compilation speed, as we have to repeatedly include subheaders. Due to a combination of our time constraints and compilation speed concerns, we haven't simulated variadic templates in our emplace functions.When variadic templates are implemented in the compiler, you can expect that we'll take advantage of them in the libraries, including in our emplace functions. We take conformance very seriously, but unfortunately, we can't do everything all at once.
It's an understandable decision. Everyone who tried just once to emulate variadic template with preprocessor horrible tricks knows how disgusting this stuff gets.
use &
in place of &
change to
<string name="magazine">Newspaper & Magazines</string>
I was facing the issue of namenode not starting. I found a solution using following:
rm -Rf <tmp dir>
(my was /usr/local/hadoop/tmp)bin/hadoop namenode -format
bin/start-all.sh
You may consider rolling back as well using checkpoint (if you had it enabled).
According to Transact-SQL Syntax Conventions (Transact-SQL) (MSDN)
Transact-SQL statement terminator. Although the semicolon is not required for most statements in this version of SQL Server, it will be required in a future version.
(also see @gerryLowry 's comment)
The exact code will vary for each of the columns you want to do, but it's likely you'll want to use the map
and apply
functions. In some cases you can just compute using the existing columns directly, since the columns are Pandas Series objects, which also work as Numpy arrays, which automatically work element-wise for usual mathematical operations.
>>> d
A B C
0 11 13 5
1 6 7 4
2 8 3 6
3 4 8 7
4 0 1 7
>>> (d.A + d.B) / d.C
0 4.800000
1 3.250000
2 1.833333
3 1.714286
4 0.142857
>>> d.A > d.C
0 True
1 True
2 True
3 False
4 False
If you need to use operations like max and min within a row, you can use apply
with axis=1
to apply any function you like to each row. Here's an example that computes min(A, B)-C
, which seems to be like your "lower wick":
>>> d.apply(lambda row: min([row['A'], row['B']])-row['C'], axis=1)
0 6
1 2
2 -3
3 -3
4 -7
Hopefully that gives you some idea of how to proceed.
Edit: to compare rows against neighboring rows, the simplest approach is to slice the columns you want to compare, leaving off the beginning/end, and then compare the resulting slices. For instance, this will tell you for which rows the element in column A is less than the next row's element in column C:
d['A'][:-1] < d['C'][1:]
and this does it the other way, telling you which rows have A less than the preceding row's C:
d['A'][1:] < d['C'][:-1]
Doing ['A"][:-1]
slices off the last element of column A, and doing ['C'][1:]
slices off the first element of column C, so when you line these two up and compare them, you're comparing each element in A with the C from the following row.
I used similar approach, but I wanted to
Code:
1. alertDialog_widget.dart
import 'dart:ui';
import 'package:flutter/material.dart';
class BlurryDialog extends StatelessWidget {
String title;
String content;
VoidCallback continueCallBack;
BlurryDialog(this.title, this.content, this.continueCallBack);
TextStyle textStyle = TextStyle (color: Colors.black);
@override
Widget build(BuildContext context) {
return BackdropFilter(
filter: ImageFilter.blur(sigmaX: 6, sigmaY: 6),
child: AlertDialog(
title: new Text(title,style: textStyle,),
content: new Text(content, style: textStyle,),
actions: <Widget>[
new FlatButton(
child: new Text("Continue"),
onPressed: () {
continueCallBack();
},
),
new FlatButton(
child: Text("Cancel"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
));
}
}
You can call this in main (or wherever you want) by creating a new method like:
_showDialog(BuildContext context)
{
VoidCallback continueCallBack = () => {
Navigator.of(context).pop(),
// code on continue comes here
};
BlurryDialog alert = BlurryDialog("Abort","Are you sure you want to abort this operation?",continueCallBack);
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
The .zip file provided by the authors is not a valid R package, and they do state that the source is for "direct use" in R (by which I assume they mean it's necessary to load the included functions manually). The non-zero exit status
simply indicates that there was an error during the installation of the "package".
You can extract the archive manually and then load the functions therein with, e.g., source('bivpois.table.R')
, or you can download the .RData file they provide and load that into the workspace with load('.RData')
. This does not install the functions as part of a package; rather, it loads the functions into your global environment, making them temporarily available.
You can download, extract, and load the .RData from R as follows:
download.file('http://stat-athens.aueb.gr/~jbn/papers/files/14/14_bivpois_RDATA.zip',
f <- tempfile())
unzip(f, exdir=tempdir())
load(file.path(tempdir(), '.RData'))
If you want the .RData file to be available in the current working directory, to be loaded in the future, you could use the following instead:
download.file('http://stat-athens.aueb.gr/~jbn/papers/files/14/14_bivpois_RDATA.zip',
f <- tempfile())
unzip(f, exdir=tempdir())
file.copy(file.path(tempdir(), '.RData'), 'bivpois.RData')
# the above copies the .RData file to a file called bivpois.RData in your current
# working directory.
load('bivpois.RData')
In future R sessions, you can just call load('bivpois.RData')
.
To start video
var videoURL = $('#playerID').prop('src');
videoURL += "&autoplay=1";
$('#playerID').prop('src',videoURL);
To stop video
var videoURL = $('#playerID').prop('src');
videoURL = videoURL.replace("&autoplay=1", "");
$('#playerID').prop('src','');
$('#playerID').prop('src',videoURL);
You may want to replace "&autoplay=1" with "?autoplay=1" incase there are no additional parameters
works for both vimeo and youtube on FF & Chrome
If you know the key name simply do like this:
delete array['key_name']
There is no best way, it depends on your use case.
Person
(you should start the name with a capital letter) is called the constructor function. This is similar to classes in other OO languages.Update: As requested examples for the third way.
Dependent properties:
The following does not work as this
does not refer to book
. There is no way to initialize a property with values of other properties in a object literal:
var book = {
price: somePrice * discount,
pages: 500,
pricePerPage: this.price / this.pages
};
instead, you could do:
var book = {
price: somePrice * discount,
pages: 500
};
book.pricePerPage = book.price / book.pages;
// or book['pricePerPage'] = book.price / book.pages;
Dynamic property names:
If the property name is stored in some variable or created through some expression, then you have to use bracket notation:
var name = 'propertyName';
// the property will be `name`, not `propertyName`
var obj = {
name: 42
};
// same here
obj.name = 42;
// this works, it will set `propertyName`
obj[name] = 42;
You probably need to break up your if statement into smaller pieces. That being said, you can do two things:
wrap the statement into do {} while (false)
and use real break
(not recommended!!! huge kludge!!!)
put the statement into its own subroutine and use return
This may be the first step to improving your code.
Another reason for similar error message is trying to mock a final
method. One shouldn't attempt to mock final methods (see Final method mocking).
I have also confronted the error in a multi-threaded test. Answer by gna worked in that case.
I encount this while I was calculating np.var(np.array([]))
. np.var
will divide size of the array which is zero in this case.
Since the release of HTML5 one can now simply do:
<div hidden>This div is hidden</div>
Note: This is not supported by some old browsers, most notably IE < 11.
I have aggregated with Qty wise data and store to dataframe
almo_grp_data = pd.DataFrame({'Qty_cnt' :
almo_slt_models_data.groupby( ['orderDate','Item','State Abv']
)['Qty'].sum()}).reset_index()
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
Based on @ZakTaccardi's answer, and assuming you don't want a single project for both flavors, add this to the end of your build.gradle
file:
def appModuleRootFolder = '.'
def srcDir = 'src'
def googleServicesJson = 'google-services.json'
task switchToStaging(type: Copy) {
outputs.upToDateWhen { false }
def flavor = 'staging'
description = "Switches to $flavor $googleServicesJson"
delete "$appModuleRootFolder/$googleServicesJson"
from "${srcDir}/$flavor/"
include "$googleServicesJson"
into "$appModuleRootFolder"
}
task switchToProduction(type: Copy) {
outputs.upToDateWhen { false }
def flavor = 'production'
description = "Switches to $flavor $googleServicesJson"
from "${srcDir}/$flavor/"
include "$googleServicesJson"
into "$appModuleRootFolder"
}
afterEvaluate {
processStagingDebugGoogleServices.dependsOn switchToStaging
processStagingReleaseGoogleServices.dependsOn switchToStaging
processProductionDebugGoogleServices.dependsOn switchToProduction
processProductionReleaseGoogleServices.dependsOn switchToProduction
}
You need to have the files src/staging/google-services.json
and src/production/google-services.json
. Replace the flavor names for the ones you use.
I had the same problem with selenium 2 in internet explorer 9, but my fix is really strange. I was not able to click into inputs inside my form -> selenium repeats, their are not visible.
It occured when my form had curved shadows -> http://www.paulund.co.uk/creating-different-css3-box-shadows-effects: in the concrete "Effect no. 2"
I have no idea, why&how this pseudo element solution's stopped selenium tests, but it works for me.
For my specific situation I resolved the problem by using window.postMessage() and eliminating any user interaction. Note that this will only work if you can somehow execute js in the parent window. Either by having it include a js from your domain, or if you have direct access to the source.
In the iframe (domain-b) i check for the presence of a cookie and if it is not set will send a postMessage to the parent (domain-a). Eg;
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1
&& document.cookie.indexOf("safari_cookie_fix") < 0) {
window.parent.postMessage(JSON.stringify({ event: "safariCookieFix", data: {} }));
}
Then in the parent window (domain-a) listen for the event.
if (typeof window.addEventListener !== "undefined") {
window.addEventListener("message", messageReceived, false);
}
function messageReceived (e) {
var data;
if (e.origin !== "http://www.domain-b.com") {
return;
}
try {
data = JSON.parse(e.data);
}
catch (err) {
return;
}
if (typeof data !== "object" || typeof data.event !== "string" || typeof data.data === "undefined") {
return;
}
if (data.event === "safariCookieFix") {
window.location.href = e.origin + "/safari/cookiefix"; // Or whatever your url is
return;
}
}
Finally on your server (http://www.domain-b.com/safari/cookiefix) you set the cookie and redirect back to where the user came from. Below example is using ASP.NET MVC
public class SafariController : Controller
{
[HttpGet]
public ActionResult CookieFix()
{
Response.Cookies.Add(new HttpCookie("safari_cookie_fix", "1"));
return Redirect(Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : "http://www.domain-a.com/");
}
}
$_SERVER['PHP_SELF']
for the page name and $_GET['id']
for a specific parameter.
try print_r($_GET);
to print out all the parameters.
for your request echo $_SERVER['PHP_SELF']."?id=".$_GET['id'];
return all the parameters echo $_SERVER['PHP_SELF']."?".$_SERVER['QUERY_STRING'];
It will work in IE7. But here you need to fixed the size
less than the number of option
and not use overflow-y:scroll
. In your example you have 2 option
but you set size=10
, which will not work.
Suppose your select has 10 option
, then fixed size=9
.
Here, in your code reference you used height:100px
with size:2
. I remove the height
css, because its not necessary and change the size:5
and it works fine.
Here is your modified code from jsfiddle:
<select size="5" style="width:100px;">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
this will generate a larger select box than size:2
create.In case of small size
the select box will not display the scrollbar,you have to check with appropriate size
quantity.Without scrollbar it will work if click on the upper and lower icons of scrollbar.I show both example in your fiddle with size:2
and size
greater than 2
(e.g: 3,5).
Here is your desired result. I think this will help you:
CSS
.wrapper{
border: 1px dashed red;
height: 150px;
overflow-x: hidden;
overflow-y: scroll;
width: 150px;
}
.wrapper .selection{
width:150px;
border:1px solid #ccc
}
HTML
<div class="wrapper">
<select size="15" class="selection">
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</div>
The SPE IDE has built-in UML creator. Just open the files in SPE and click on the UML tab.
I don't know how comprhensive it is for your needs, but it doesn't require any additional downloads or configurations to use.
This should work, at least according to the Search Filter Syntax article on MSDN network.
The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.
You may also try separating the filter into two parts:
(|(displayName=*searchstring)(displayName=searchstring*))
in my case the right server name was the name of my computer. for example John-PC, or somth
Please check your project/module language levels (Project Structure | Project; Project Structure | Modules | module-name | Sources). You might also want to take a look at Settings | Compiler | Java Compiler | Per-module bytecode version.
Set also this:
File -> Project Structure -> Modules :: Sources (next to Paths and Dependencies) and that has a "Language level" option which also needs to be set correctly.
I have created a library matrix-slicer to manipulate with matrix items. So your problem could be solved like this:
var m = new Matrix([
[1, 2],
[3, 4],
]);
m.getColumn(1); // => [2, 4]
Possible it will be useful for somebody. ;-)
$("#Id").change(function(){
var selected = $('#Id option:selected').val();
alert(selected);
});
I think this is what you need.
To create a new commit that 'undoes' the changes of a past commit, use:
$ git revert <commit-hash>
It's also possible to actually remove a commit from an arbitrary point in the past by rebasing and then resetting, but you really don't want to do that if you have already pushed your commits to another repository (or someone else has pulled from you).
If your previous commit is a merge commit you can run this command
$ git revert -m 1 <commit-hash>
See schacon.github.com/git/howto/revert-a-faulty-merge.txt for proper ways to re-merge an un-merged branch
One of the biggest reasons that C++ doesn't have built in garbage collection is that getting garbage collection to play nice with destructors is really, really hard. As far as I know, nobody really knows how to solve it completely yet. There are alot of issues to deal with:
These are just a few of the problems faced.
The example below shows the basic usage of the FileReader
to read the contents of an uploaded file. Here is a working Plunker of this example.
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>
script.js
function init(){
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event){
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event){
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
This works for me :
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
$scope.actions.data = $scope.actions.data.concat(data)
From here: http://forums.oracle.com/forums/thread.jspa?messageID=2354075
alter session set skip_unusable_indexes = true;
alter index your_index unusable;
do import...
alter index your_index rebuild [online];
Hey i have posted a video tutorial on youtube about this, you can check that and you can find here the sample code :
http://myfundatimemachine.blogspot.in/2012/06/database-connection-to-java-application.html
If you are looking for a form reset:
<input type="reset" value="Reset Form Values"/>
or to reset other aspects of the form not handled by the browser
<input type="reset" onclick="doFormReset();" value="Reset Form Values"/>
Using jQuery
function doFormReset(){
$(".invalid").removeClass("invalid");
}
Generate random number between 0 to 99:
int x = arc4random()%100;
Generate random number between 500 and 1000:
int x = (arc4random()%501) + 500;
A self-made solution:
bool isNumeric(const char *str)
{
while(*str != '\0')
{
if(*str < '0' || *str > '9')
return false;
str++;
}
return true;
}
Note that this solution should not be used in production-code, because it has severe limitations. But I like it for understanding C-Strings and ASCII.
That is pretty much how you do it. However, there is a shorter syntax you can use.
sSession = (string)Session["variable"] ?? "set this";
This is saying if the session variables is null, set sSession to "set this"
Actually whatever the third parameter is, 0 or 1 or 2, it will not round your value.
CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))
I was just wondering how the random number generator in C# works.
That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.
I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.
You can use Random.Next(int, int)
:
Random rng = new Random();
for (int i = 0; i < 10; i++)
{
Console.WriteLine(rng.Next(1, 101));
}
Note that the upper bound is exclusive - which is why I've used 101 here.
You should also be aware of some of the "gotchas" associated with Random
- in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.
Ran into this issue with Parallels and VS 2013. Command + Insert also fixed it in my setup, in addition to the accepted answer. On my Windows USB keyboard Command == WindowsKey.
When using "jsonp", you would basically be returning data wrapped in a function call, something like
jsonpCallback([{"id":1,"value":"testing"},{"id":2,"value":"test again"}])
where the function/callback name is 'jsonpCallback'.
If you have access to the server, please first verify that the response is in the correct "jsonp"
format
For such a response coming from the server, you would need to specify something in the ajax call as well, something like
jsonpCallback: "jsonpCallback", in your ajax call
Please note that the name of the callback does not need to be "jsonpCallback
" its just a name picked as an example but it needs to match the name(wrapping) done on the server side.
My first guess to your problem is that the response from the server is not what it should be.
Just for completeness, you can get a list of kernels with jupyter kernelspec list
, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel
. If you do not see everything in this list when you run jupyter kernelspec list
, try looking in common Jupyter folders:
ls ~/.local/share/jupyter/kernels # usually where local kernels go
ls /usr/local/share/jupyter/kernels # usually where system-wide kernels go
ls /usr/share/jupyter/kernels # also where system-wide kernels can go
Also, you can delete a kernel with jupyter kernelspec remove
or jupyter kernelspec uninstall
. The latter is an alias for remove
. From the in-line help text for the command:
uninstall
Alias for remove
remove
Remove one or more Jupyter kernelspecs by name.
Use the below code:
import base64
#Taking input through the terminal.
welcomeInput= raw_input("Enter 1 to convert String to Base64, 2 to convert Base64 to String: ")
if(int(welcomeInput)==1 or int(welcomeInput)==2):
#Code to Convert String to Base 64.
if int(welcomeInput)==1:
inputString= raw_input("Enter the String to be converted to Base64:")
base64Value = base64.b64encode(inputString.encode())
print "Base64 Value = " + base64Value
#Code to Convert Base 64 to String.
elif int(welcomeInput)==2:
inputString= raw_input("Enter the Base64 value to be converted to String:")
stringValue = base64.b64decode(inputString).decode('utf-8')
print "Base64 Value = " + stringValue
else:
print "Please enter a valid value."
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
It's incorrect, but you can try this instead:
select
a.x,
( select b.y from b where b.v = a.v) as by,
( select b.z from b where b.v = a.v) as bz
from a
you can also use subquery in join
select
a.x,
b.y,
b.z
from a
left join (select y,z from b where ... ) b on b.v = a.v
or
select
a.x,
b.y,
b.z
from a
left join b on b.v = a.v
Had the same issue and what worked for me was:
Checking the ownership of /var/run/docker.sock
ls -l /var/run/docker.sock
If you're not the owner then change ownership with the command
sudo chown *your-username* /var/run/docker.sock
Then you can go ahead and try executing the docker commands hassle-free :D
Individual components of a filename (i.e. each subdirectory along the path, and the final filename) are limited to 255 characters, and the total path length is limited to approximately 32,000 characters.
However, on Windows, you can't exceed MAX_PATH
value (259 characters for files, 248 for folders). See http://msdn.microsoft.com/en-us/library/aa365247.aspx for full details.
I literally striped out this line of code from content-single-popup.php located in woocommerce folder in my theme directory.
global $product;
echo $product->get_categories( ', ', ' ' . _n( ' ', ' ', $cat_count, 'woocommerce' ) . ' ', ' ' );
Since my theme that I am working on has integrated woocommerce in it, this was my solution.
Splendid answer from Ben. However I'm surprised that the Affinity Propagation (AP) method has been here suggested just to find the number of cluster for the k-means method, where in general AP do a better job clustering the data. Please see the scientific paper supporting this method in Science here:
Frey, Brendan J., and Delbert Dueck. "Clustering by passing messages between data points." science 315.5814 (2007): 972-976.
So if you are not biased toward k-means I suggest to use AP directly, which will cluster the data without requiring knowing the number of clusters:
library(apcluster)
apclus = apcluster(negDistMat(r=2), data)
show(apclus)
If negative euclidean distances are not appropriate, then you can use another similarity measures provided in the same package. For example, for similarities based on Spearman correlations, this is what you need:
sim = corSimMat(data, method="spearman")
apclus = apcluster(s=sim)
Please note that those functions for similarities in the AP package are just provided for simplicity. In fact, apcluster() function in R will accept any matrix of correlations. The same before with corSimMat() can be done with this:
sim = cor(data, method="spearman")
or
sim = cor(t(data), method="spearman")
depending on what you want to cluster on your matrix (rows or cols).
As jzd says, you can use System.currentTimeMillis
. If you need it in a Date
object but don't want to create a new Date
object, you can use Date.setTime
to reuse an existing Date
object. Personally I hate the fact that Date
is mutable, but maybe it's useful to you in this particular case. Similarly, Calendar
has a setTimeInMillis
method.
If possible though, it would probably be better just to keep it as a long
. If you only need a timestamp, effectively, then that would be the best approach.
Set the FOREIGN_KEY_CHECKS before and after your delete SQL statements.
SET FOREIGN_KEY_CHECKS = 0;
DELETE FROM table WHERE ...
DELETE FROM table WHERE ...
DELETE FROM table WHERE ...
SET FOREIGN_KEY_CHECKS = 1;
Source: https://alvinalexander.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys.
On my system: CentOS 5
I can use \s
outside of collections but have to use [:space:]
inside of collections. In fact I can use [:space:]
only inside collections. So to match a single space using this I have to use [[:space:]]
Which is really strange.
echo a b cX | sed -r "s/(a\sb[[:space:]]c[^[:space:]])/Result: \1/"
Result: a b cX
\s
[[:space:]]
[^[:space:]]
These two will not work:
a[:space:]b instead use a\sb or a[[:space:]]b
a[^\s]b instead use a[^[:space:]]b
You are missing #
hash character before id selectors, this should work:
$(document).ready(function() {
$("#div2").hide();
$("#preview").click(function() {
$("#div1").hide();
$("#div2").show();
});
});
Be careful, because none of these methods work with a large number of files. Personally, I used this line:
for i in $(ls | grep ".txt");do cat $i >> output.txt;done
EDIT: As someone said in the comments, you can replace $(ls | grep ".txt")
with $(ls *.txt)
EDIT: thanks to @gnourf_gnourf expertise, the use of glob is the correct way to iterate over files in a directory. Consequently, blasphemous expressions like $(ls | grep ".txt")
must be replaced by *.txt
(see the article here).
Good Solution
for i in *.txt;do cat $i >> output.txt;done
Actually the easiest way to change (only) port in development Django server is just like:
python manage.py runserver 7000
that should run development server on http://127.0.0.1:7000/
If you are trying to do basic auth, you can try this:
const username = ''
const password = ''
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const url = 'https://...'
const data = {
...
}
axios.post(url, data, {
headers: {
'Authorization': `Basic ${token}`
},
})
This worked for me. Hope that helps
examples without brackets:
void function (msg) { alert(msg); }
('SO');
(this is the only real use of void, afaik)
or
var a = function (msg) { alert(msg); }
('SO');
or
!function (msg) { alert(msg); }
('SO');
work as well. the void
is causing the expression to evaluate, as well as the assignment and the bang. the last one works with ~
, +
, -
, delete
, typeof
, some of the unary operators (void
is one as well). not working are of couse ++
, --
because of the requirement of a variable.
the line break is not necessary.
If you declare a DateTime, then the default value is DateTime.MinValue, and hence you have to check it like this:
DateTime dat = new DateTime();
if (dat==DateTime.MinValue)
{
//unassigned
}
If the DateTime is nullable, well that's a different story:
DateTime? dat = null;
if (!dat.HasValue)
{
//unassigned
}
When you stop an instance, it is 'deleted'. As such there's nothing to be charged for. If you have an Elastic IP or EBS, then you'll be charged for those - but nothing related to the instance itself.
In Swift 3.0 you can get the appdelegate
reference by
let appDelegate = UIApplication.shared.delegate as! AppDelegate
PostgreSQL supports regular expressions matching.
So, your example would look like
SELECT * FROM books WHERE title ~ '^\d+ ?'
This will match a title starting with one or more digits and an optional space
It's because you're casting to the wrong thing - you're trying to convert to a particular type, and the object that your express refers to is incompatible with that type. For example:
Object x = "this is a string";
InputStream y = (InputStream) x; // This will throw ClassCastException
If you could provide a code sample, that would really help...
If you're running this on a Linux/Unix host, the easiest solution would be to use exec()
or similar to run the command wc -l $path
. Just make sure you've sanitized $path
first to be sure that it isn't something like "/path/to/file ; rm -rf /".
Do you need to do it from mgmt studio? Here's how we do it from cmd line:
"C:\Program Files\Microsoft SQL Server\MSSQL\Binn\TEXTCOPY.exe" /S < Server> /D < DataBase> /T mytable /C mypictureblob /F "C:\picture.png" /W"where RecId=" /I
You can combine this all into one formula, but you need to use a regular IF
first to find out if the VLOOKUP
came back with something, then use your COUNTIF
if it did.
=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))
In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).
to chnage line endings from LF to CRLF:
open Sublime and follow the steps:-
1 press Ctrl+shift+p then install package name line unify endings
then again press Ctrl+shift+p
2 in the blank input box type "Line unify ending "
3 Hit enter twice
Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF
As suggested this may be an issue with your compiler version.
Try using the following code to convert a long
to std::string
:
#include <sstream>
#include <string>
#include <iostream>
int main() {
std::ostringstream ss;
long num = 123456;
ss << num;
std::cout << ss.str() << std::endl;
}
I faced a similar kind of issue while using a custom object as a key in Treemap. Whenever you are using a custom object as a key in hashmap then you override two function equals and hashcode, However if you are using ContainsKey method of Treemap on this object then you need to override CompareTo method as well otherwise you will be getting this error Someone using a custom object as a key in hashmap in kotlin should do like following
data class CustomObjectKey(var key1:String = "" , var
key2:String = ""):Comparable<CustomObjectKey?>
{
override fun compareTo(other: CustomObjectKey?): Int {
if(other == null)
return -1
// suppose you want to do comparison based on key 1
return this.key1.compareTo((other)key1)
}
override fun equals(other: Any?): Boolean {
if(other == null)
return false
return this.key1 == (other as CustomObjectKey).key1
}
override fun hashCode(): Int {
return this.key1.hashCode()
}
}
I think you just need;
List<string> list = new List<string>();
list.Add("hai");
There is a difference between
List<string> list;
and
List<string> list = new List<string>();
When you didn't use new
keyword in this case, your list
didn't initialized. And when you try to add it hai
, obviously you get an error.
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
"Using HTML5/Canvas/JavaScript to take screenshots" answers your problem.
You can use JavaScript/Canvas to do the job but it is still experimental.
This specifies the default collation for the database. Every text field that you create in tables in the database will use that collation, unless you specify a different one.
A database always has a default collation. If you don't specify any, the default collation of the SQL Server instance is used.
The name of the collation that you use shows that it uses the Latin1 code page 1, is case insensitive (CI) and accent sensitive (AS). This collation is used in the USA, so it will contain sorting rules that are used in the USA.
The collation decides how text values are compared for equality and likeness, and how they are compared when sorting. The code page is used when storing non-unicode data, e.g. varchar fields.
Try to use this alternate query:
SELECT A.CONTACTID
FROM (SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'VOLUNTEER')A ,
(SELECT CONTACTID FROM TESTTBL WHERE FLAG = 'UPLOADED') B WHERE A.CONTACTID = B.CONTACTID;
write this code
scp -r -o "ForwardAgent=yes" /Users/pengge/11.vim [email protected]:/root/
If you have a SSH key with access to the destination server and the source server does not, adding -o "ForwardAgent=yes" will allow you to forward your SSH agent to the source server so that it can use your SSH key to connect to the destination server.
spans default to inline style, which you can't specify the width of.
display: inline-block;
would be a good way, except IE doesn't support it
you can, however, hack a multiple browser solution
From laravel 5.3 only using get()
method you can get specific columns of your table:
YouModelName::get(['id', 'name']);
Or from laravel 5.4 you can also use all()
method for getting the fields of your choice:
YourModelName::all('id', 'name');
with both of above method get()
or all()
you can also use where()
but syntax is different for both:
Model::all()
YourModelName::all('id', 'name')->where('id',1);
Model::get()
YourModelName::where('id',1)->get(['id', 'name']);
As of iOS 5, the simulator has a configurable location.
Under the Debug menu, the last entry is "Location"; this gives you a sub menu with:
Custom Location lets you enter a Lat/Long value. Bicycle ride, City Run, and Freeway Drive are simulation of a moving location (in Cupertino, of course).
Of course, this does nothing to help with debugging for iOS 4 (or earlier); but it's a definite improvement!
Are you import them? Like this:
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:recyclerview-v7:21.0.3'
with the help of below commands your application will work as you aspected run each command as I mention
1.npm list -g --depth=0
2.npm i npm-check-updates
3.npm install
and finally, run the below command to open your project in browser
ng serve --open
You are probably seeking:
ActiveRecord::Base.connection.tables
and
ActiveRecord::Base.connection.columns('projects').map(&:name)
You should probably wrap them in shorter syntax inside your .irbrc
.
To add to the other answers. I had the same problem and this is the code i used in my express server to allow REST calls:
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'URLs to trust of allow');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
if ('OPTIONS' == req.method) {
res.sendStatus(200);
} else {
next();
}
});
What this code basically does is intercepts all the requests and adds the CORS headers, then continue with my normal routes. When there is a OPTIONS request it responds only with the CORS headers.
EDIT: I was using this fix for two separate nodejs express servers on the same machine. In the end I fixed the problem with a simple proxy server.
Note: this is JQuery. See Sébastien answer for Javascript
$(function() {
var temp="a";
$("#MySelect").val(temp);
});
<select name="MySelect" id="MySelect">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Go with a triple negative:
If (Not Not FileNamesList) <> 0 Then
' Array has been initialized, so you're good to go.
Else
' Array has NOT been initialized
End If
Or just:
If (Not FileNamesList) = -1 Then
' Array has NOT been initialized
Else
' Array has been initialized, so you're good to go.
End If
In VB, for whatever reason, Not myArray
returns the SafeArray pointer. For uninitialized arrays, this returns -1. You can Not
this to XOR it with -1, thus returning zero, if you prefer.
(Not myArray) (Not Not myArray)
Uninitialized -1 0
Initialized -someBigNumber someOtherBigNumber
The JPanel
is actually only a container where you can put different elements in it (even other JPanels
). So in your case I would suggest one big JPanel
as some sort of main container for your window. That main panel you assign a Layout
that suits your needs ( here is an introduction to the layouts).
After you set the layout to your main panel you can add the paint panel and the other JPanels you want (like those with the text in it..).
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
JPanel paintPanel = new JPanel();
JPanel textPanel = new JPanel();
mainPanel.add(paintPanel);
mainPanel.add(textPanel);
This is just an example that sorts all sub panels vertically (Y-Axis). So if you want some other stuff at the bottom of your mainPanel (maybe some icons or buttons) that should be organized with another layout (like a horizontal layout), just create again a new JPanel as a container for all the other stuff and set setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS)
.
As you will find out, the layouts are quite rigid and it may be difficult to find the best layout for your panels. So don't give up, read the introduction (the link above) and look at the pictures – this is how I do it :)
Or you can just use NetBeans to write your program. There you have a pretty easy visual editor (drag and drop) to create all sorts of Windows and Frames. (only understanding the code afterwards is ... tricky sometimes.)
Since there are some many people interested in this question, I wanted to provide a complete example of how to layout a JFrame to make it look like OP wants it to.
The class is called MyFrame and extends swings JFrame
public class MyFrame extends javax.swing.JFrame{
// these are the components we need.
private final JSplitPane splitPane; // split the window in top and bottom
private final JPanel topPanel; // container panel for the top
private final JPanel bottomPanel; // container panel for the bottom
private final JScrollPane scrollPane; // makes the text scrollable
private final JTextArea textArea; // the text
private final JPanel inputPanel; // under the text a container for all the input elements
private final JTextField textField; // a textField for the text the user inputs
private final JButton button; // and a "send" button
public MyFrame(){
// first, lets create the containers:
// the splitPane devides the window in two components (here: top and bottom)
// users can then move the devider and decide how much of the top component
// and how much of the bottom component they want to see.
splitPane = new JSplitPane();
topPanel = new JPanel(); // our top component
bottomPanel = new JPanel(); // our bottom component
// in our bottom panel we want the text area and the input components
scrollPane = new JScrollPane(); // this scrollPane is used to make the text area scrollable
textArea = new JTextArea(); // this text area will be put inside the scrollPane
// the input components will be put in a separate panel
inputPanel = new JPanel();
textField = new JTextField(); // first the input field where the user can type his text
button = new JButton("send"); // and a button at the right, to send the text
// now lets define the default size of our window and its layout:
setPreferredSize(new Dimension(400, 400)); // let's open the window with a default size of 400x400 pixels
// the contentPane is the container that holds all our components
getContentPane().setLayout(new GridLayout()); // the default GridLayout is like a grid with 1 column and 1 row,
// we only add one element to the window itself
getContentPane().add(splitPane); // due to the GridLayout, our splitPane will now fill the whole window
// let's configure our splitPane:
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); // we want it to split the window verticaly
splitPane.setDividerLocation(200); // the initial position of the divider is 200 (our window is 400 pixels high)
splitPane.setTopComponent(topPanel); // at the top we want our "topPanel"
splitPane.setBottomComponent(bottomPanel); // and at the bottom we want our "bottomPanel"
// our topPanel doesn't need anymore for this example. Whatever you want it to contain, you can add it here
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.Y_AXIS)); // BoxLayout.Y_AXIS will arrange the content vertically
bottomPanel.add(scrollPane); // first we add the scrollPane to the bottomPanel, so it is at the top
scrollPane.setViewportView(textArea); // the scrollPane should make the textArea scrollable, so we define the viewport
bottomPanel.add(inputPanel); // then we add the inputPanel to the bottomPanel, so it under the scrollPane / textArea
// let's set the maximum size of the inputPanel, so it doesn't get too big when the user resizes the window
inputPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 75)); // we set the max height to 75 and the max width to (almost) unlimited
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.X_AXIS)); // X_Axis will arrange the content horizontally
inputPanel.add(textField); // left will be the textField
inputPanel.add(button); // and right the "send" button
pack(); // calling pack() at the end, will ensure that every layout and size we just defined gets applied before the stuff becomes visible
}
public static void main(String args[]){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
new MyFrame().setVisible(true);
}
});
}
}
Please be aware that this is only an example and there are multiple approaches to layout a window. It all depends on your needs and if you want the content to be resizable / responsive. Another really good approach would be the GridBagLayout which can handle quite complex layouting, but which is also quite complex to learn.
Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq
Save your JSON example to a file, say ex.json and then
yq -y '.' ex.json
AAPL:
- shares: -75.088
date: 11/27/2015
- shares: 75.088
date: 11/26/2015
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
After I do "Build->clean project" and "Sync project with gradle". Both them are not resolve. I down build gradle version from 3.3.0 => 3.2.1 (revert as project init state) and it resolve my problem.
Use:
echo %time% & dir & echo %time%
This is, from memory, equivalent to the semi-colon separator in bash
and other UNIXy shells.
There's also &&
(or ||
) which only executes the second command if the first succeeded (or failed), but the single ampersand &
is what you're looking for here.
That's likely to give you the same time however since environment variables tend to be evaluated on read rather than execute.
You can get round this by turning on delayed expansion:
pax> cmd /v:on /c "echo !time! & ping 127.0.0.1 >nul: & echo !time!"
15:23:36.77
15:23:39.85
That's needed from the command line. If you're doing this inside a script, you can just use setlocal
:
@setlocal enableextensions enabledelayedexpansion
@echo off
echo !time! & ping 127.0.0.1 >nul: & echo !time!
endlocal
I disagree SpringJPA makes live easy. Yes, it provides some classes and you can make some simple DAO fast, but in fact, it's all you can do. If you want to do something more than findById() or save, you must go through hell:
Why own transaction management is an disadvantage? Since Java 1.8 allows default methods into interfaces, Spring annotation based transactions, simple doesn't work.
Unfortunately, SpringJPA is based on reflections, and sometimes you need to point a method name or entity package into annotations (!). That's why any refactoring makes big crash. Sadly, @Transactional works for primary DS only :( So, if you have more than one DataSources, remember - transactions works just for primary one :)
What are the main differences between Hibernate and Spring Data JPA?
Hibernate is JPA compatibile, SpringJPA Spring compatibile. Your HibernateJPA DAO can be used with JavaEE or Hibernate Standalone, when SpringJPA can be used within Spring - SpringBoot for example
When should we not use Hibernate or Spring Data JPA? Also, when may Spring JDBC template perform better than Hibernate / Spring Data JPA?
Use Spring JDBC only when you need to use much Joins or when you need to use Spring having multiple datasource connections. Generally, avoid JPA for Joins.
But my general advice, use fresh solution—Daobab (http://www.daobab.io). Daobab is my Java and any JPA engine integrator, and I believe it will help much in your tasks :)
Create a macro and use the following code to grab the data and put it in a new sheet (Sheet2):
Dim strValue As String
Dim strCellNum As String
Dim x As String
x = 1
For i = 1 To 700 Step 7
strCellNum = "A" & i
strValue = Worksheets("Sheet1").Range(strCellNum).Value
Debug.Print strValue
Worksheets("Sheet2").Range("A" & x).Value = strValue
x = x + 1
Next
Let me know if this helps! JFV
Posting as answer, as I don't have the privilege to comment.
Point to note: follow the accepted answer posted by "That Dave Guy".
After setting the variables, make sure you set the appropriate permissions to the java directory where it's installed.
chmod -R 755 /usr/java
$next_id = mysql_fetch_assoc(mysql_query("SELECT MAX(id) FROM table"));
$next_id['MAX(id)']; // next auto incr id
hope it helpful :)
push
does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action){
console.log(arr);
switch (action.type){
case ADD_ITEM :
return {
...state,
arr:[...state.arr, action.newItem]
}
default:return state
}
}
In a word - speed. An index for up to a million rows fits in a 32-bit word, so it can be used efficiently on 32-bit processors. Function arguments that fit in a CPU register are extremely efficient, while ones that are larger require accessing memory on each function call, a far slower operation. Updating a spreadsheet can be an intensive operation involving many cell references, so speed is important. Besides, the Excel team expects that anyone dealing with more than a million rows will be using a database rather than a spreadsheet.
I think I got it. It's:
"SVN Client Path" /command:update / path:"My folder path"
faced the same problem: Gradle sync failed: failed to find Build Tools revision x.x.x
reason: the build tools for that version was not down loaded properly solution:
then follow the steps 1 to 3 and 6.
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
This solution runs only one loop and has the minimun object to map numerals to roman letters
function RomantoNumeral(r){
let result = 0,
keys = {M:1000, D:500, C:100, L:50, C:100, L:50, X:10, V:5, I:1},
order = Object.keys(keys),
rom = Array.from(r)
rom.forEach((e, i)=>{
if( i < rom.length -1 && order.indexOf(e) > order.indexOf(rom[i+1])){
result -= keys[e]
} else {
result +=keys[e]
}
})
return result
}
RomantoNumeral('MMDCCCXXXVII') #2837
The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.
If someone is using frameworks like scrapy
the you will have to use /html/body//a[contains(@href,'com')][2]/@href
along with get() like this:
response.xpath('//a[contains(@href,'com')][2]/@href').get()
For me above solutions didn't work then I tried
map.setCenter(new google.maps.LatLng(lat, lng));
and it worked as expected.
Are you looking for a Windows API?
Just use SHGetFolderPath function with CSIDL_INTERNET_CACHE flag or SHGetKnownFolderPath with FOLDERID_InternetCache flag to get the exact location. This way you don't have to worry about the OS. The former function works in Windows XP. The latter one works in Windows Vista+.
Just use it like it was an object you defined. i.e.
$trends = $json_output->trends;
If the list implementation you're using is IEnumerable<T>
and Linq is an option, you can use Any
:
if (!list.Any()) {
}
Otherwise you generally have a Length
or Count
property on arrays and collection types respectively.
You can't. They simply do not work that way. A drop down menu must have one of its options selected at all times.
You could (although I don't recommend it) watch for a change event and then use JS to delete the first option if it is blank.
If you want the text value of a QString object you can use the __str__
property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.
This Works For me !!!
Call a Function without Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers();
});
Call a Function with Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers($(e1.target).val());
});
We can Supply parameter in different way after some search I found some useful
<plugin>
<artifactId>${release.artifactId}</artifactId>
<version>${release.version}-${release.svm.version}</version>...
...
Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .
While Running build we need supply value for those parameter as follows.
RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74
Here I am supplying
release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74
It worked for me. Thanks
If the sources are spread in many folders, and it makes sense to have individual Makefiles then as suggested before, recursive make is a good approach, but for smaller projects I find it easier to list all the source files in the Makefile with their relative path to the Makefile like this:
# common sources
COMMON_SRC := ./main.cpp \
../src1/somefile.cpp \
../src1/somefile2.cpp \
../src2/somefile3.cpp \
I can then set VPATH
this way:
VPATH := ../src1:../src2
Then I build the objects:
COMMON_OBJS := $(patsubst %.cpp, $(ObjDir)/%$(ARCH)$(DEBUG).o, $(notdir $(COMMON_SRC)))
Now the rule is simple:
# the "common" object files
$(ObjDir)/%$(ARCH)$(DEBUG).o : %.cpp Makefile
@echo creating $@ ...
$(CXX) $(CFLAGS) $(EXTRA_CFLAGS) -c -o $@ $<
And building the output is even easier:
# This will make the cbsdk shared library
$(BinDir)/$(OUTPUTBIN): $(COMMON_OBJS)
@echo building output ...
$(CXX) -o $(BinDir)/$(OUTPUTBIN) $(COMMON_OBJS) $(LFLAGS)
One can even make the VPATH
generation automated by:
VPATH := $(dir $(COMMON_SRC))
Or using the fact that sort
removes duplicates (although it should not matter):
VPATH := $(sort $(dir $(COMMON_SRC)))
Use a DataTrigger
:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
Arrays.asList("Ryan", "Julie", "Bob");
A fast approach is to use the following according to ie that you want to focus (check the comments), inside your css files (where margin-top, set whatever css attribute you like):
margin-top: 10px\9; /*It will apply to all ie from 8 and below */
*margin-top: 10px; /*It will apply to ie 7 and below */
_margin-top: 10px; /*It will apply to ie 6 and below*/
A better approach would be to check user agent or a conditional if, in order to avoid the loading of unnecessary CSS in other browsers.
All modal/lightbox javascript-based systems use an overflow when displaying the modal/lightbox, on html tag or body tag.
When lightbox is show, the js push a overflow hidden on html or body tag. When lightbox is hidden, some remove the hidden other push a overflow auto on html or body tag.
Developers who work on Mac, do not see the problem of the scrollbar.
Just replace the hidden by an unset not to see the content slipping under the modal of the removal of the scrollbar.
Lightbox open/show:
<html style="overflow: unset;"></html>
Lightbox close/hide:
<html style="overflow: auto;"></html>
In today's date this solution works for me:
/**
* A generic confirmation for risky actions.
* Usage: Add attributes: ng-really-message="Are you sure"? ng-really-click="takeAction()" function
*/
angular.module('app').directive('ngReallyClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('click', function() {
var message = attrs.ngReallyMessage;
if (message && confirm(message)) {
scope.$apply(attrs.ngReallyClick);
}
});
}
}
}]);
Credits:https://gist.github.com/asafge/7430497#file-ng-really-js
SourceTree is a git GUI which has a pretty convenient interface for staging just the bits you want. It does not have anything remotely similar for amending a proper revision.
So git reset --soft HEAD~1
is much more useful than commit --amend
in this scenario. I can undo the commit, get all the changes back into the staging area, and resume tweaking the staged bits using SourceTree.
Really, it seems to me that commit --amend
is the more redundant command of the two, but git is git and does not shy away from similar commands that do slightly different things.
Also relevant, but specially to excel, look at this answer and this other one that suggests, inserting a line at the beginning of the CSV with
"sep=,"
To inform excel which separator to expect
You should do something like this:
if !(string?.isEmpty ?? true) { //Not nil nor empty }
Nil coalescing operator checks if the optional is not nil, in case it is not nil it then checks its property, in this case isEmpty. Because this optional can be nil you provide a default value which will be used when your optional is nil.
First, {"value": .value} can be abbreviated to just {value}.
Second, the --argfile option (available in jq 1.4 and jq 1.5) may be of interest as it avoids having to use the --slurp option.
Putting these together, the two objects in the two files can be combined in the specified way as follows:
$ jq -n --argfile o1 file1 --argfile o2 file2 '$o1 * $o2 | {value}'
The '-n' flag tells jq not to read from stdin, since inputs are coming from the --argfile options here.
The jq manual deprecates --argfile
because its semantics are non-trivial: if the specified input file contains exactly one JSON entity, then that entity is read as is; otherwise, the items in the stream are wrapped in an array.
If you are uncomfortable using --argfile, there are several alternatives you may wish to consider. In doing so, be assured that using --slurpfile
does not incur the inefficiencies of the -s
command-line option when the latter is used with multiple files.
Add the 'columns' parameter:
frame = pd.DataFrame({
'one thing':[1,2,3,4],
'second thing':[0.1,0.2,1,2],
'other thing':['a','e','i','o']},
columns=['one thing', 'second thing', 'other thing']
)
public static boolean isValidType(Class<?> retType)
{
if (retType.isPrimitive() && retType != void.class) return true;
if (Number.class.isAssignableFrom(retType)) return true;
if (AbstractCode.class.isAssignableFrom(retType)) return true;
if (Boolean.class == retType) return true;
if (Character.class == retType) return true;
if (String.class == retType) return true;
if (Date.class.isAssignableFrom(retType)) return true;
if (byte[].class.isAssignableFrom(retType)) return true;
if (Enum.class.isAssignableFrom(retType)) return true;
return false;
}
Originally there was just 302
Response | What browsers should do |
---|---|
302 Found |
Redo request with new url |
The idea is that:
GET
at some location, you would redo your GET
to the new URLPOST
at some location, you would redo your POST
to the new URLPUT
at some location, you would redo your PUT
to the new URLDELETE
at some location, you would redo your DELETE
to the new URLUnfortunately every browser did it wrong. When getting a 302
, they would always switch to GET
at the new URL, rather than retrying the request with the same verb (e.g., POST
):
It became de-facto wrong.
All browsers got 302
wrong. So 303
and 307
were created.
Response | What browsers should do | What browsers actually do |
---|---|---|
302 Found |
Redo request with new url | GET with new url |
303 See Other |
GET with new url | GET with new url |
307 Temporary Redirect |
Redo request with new url | Redo request with new url |
The 5 different kinds of redirects:
+------------------------------------------------------------+
¦ ¦ Switch to GET? ¦
¦ ¦------------------------------------------------¦
¦ Temporary ¦ No ¦ Yes ¦
¦-----------+------------------------+-----------------------¦
¦ No ¦ 308 Permanent Redirect ¦ 301 Moved Permanently ¦
¦-----------+------------------------+-----------------------¦
¦ Yes ¦ 307 Temporary Redirect ¦ 303 See Other ¦
¦ ¦ 302 Found (intended) ¦ 302 Found (actual) ¦
+------------------------------------------------------------+
Alternatively:
Response | Switch to get? | Temporary? |
---|---|---|
301 Moved Permanently |
No | No |
302 Found (intended) |
No | Yes |
302 Found (actual) |
Yes | Yes |
303 See Other |
Yes | Yes |
307 Temporary Redirect |
No | Yes |
308 Permanent Redirect |
No | No |
for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).
function iAsk(lvl){
var i=0;
var intr =setInterval(function(){ // start the loop
i++; // increment it
if(i>lvl){ // check if the end round reached.
clearInterval(intr);
return;
}
setTimeout(function(){
$(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
},50);
setTimeout(function(){
// do another bla bla bla after 100 millisecond.
seq[i-1]=(Math.ceil(Math.random()*4)).toString();
$("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
$("#d"+seq[i-1]).prop("src",pGif);
var d =document.getElementById('aud');
d.play();
},100);
setTimeout(function(){
// keep adding bla bla bla till you done :)
$("#d"+seq[i-1]).prop("src",pPng);
},900);
},1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
}
PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.
PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..
Do you mean this?
var listOfList = new List<List<int>>() {
new List<int>() { 1, 2 },
new List<int>() { 3, 4 },
new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));
foreach (var x in result) Console.WriteLine(x);
Results in: 9 9 9 1 2 3 4 5 6
I added below Path in environment variable
C:\Program Files\Java\jdk1.8.0_91\bin
and then compiled the program but got the error then I restarted the system and again compiled the program
This time it worked :)
The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).
Define a Java class that resembles the JSON you will be expecting.
e.g. this JSON:
{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}
could be mapped to this class:
public class Fizzle{
private List<String> foo;
private boolean bar;
private int baz;
// getters and setters omitted
}
Now if you have a Controller method like this:
@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
return new Fozzle(input);
}
and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json
.
For a full working example see this previous answer of mine.
No, @media
rules and media queries cannot exist in inline style attributes as they can only contain property: value
declarations. As the spec puts it:
The value of the style attribute must match the syntax of the contents of a CSS declaration block
The only way to apply styles to an element only in certain media is with a separate rule in your stylesheet, which means you'll need to come up with a selector for it.
A dummy span
selector would look like this, but if you're targeting a very specific element you will need a more specific selector:
span { background-image: url(particular_ad.png); }
@media (max-width: 300px) {
span { background-image: url(particular_ad_small.png); }
}
A) To control sys.getdefaultencoding()
output:
python -c 'import sys; print(sys.getdefaultencoding())'
ascii
Then
echo "import sys; sys.setdefaultencoding('utf-16-be')" > sitecustomize.py
and
PYTHONPATH=".:$PYTHONPATH" python -c 'import sys; print(sys.getdefaultencoding())'
utf-16-be
You could put your sitecustomize.py higher in your PYTHONPATH
.
Also you might like to try reload(sys).setdefaultencoding
by @EOL
B) To control stdin.encoding
and stdout.encoding
you want to set PYTHONIOENCODING
:
python -c 'import sys; print(sys.stdin.encoding, sys.stdout.encoding)'
ascii ascii
Then
PYTHONIOENCODING="utf-16-be" python -c 'import sys;
print(sys.stdin.encoding, sys.stdout.encoding)'
utf-16-be utf-16-be
Finally: you can use A) or B) or both!
The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.
What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!
I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.
So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;
// create and initialize an object
public static JSONObject buildObject( final SimpleEntry... entries ) {
JSONObject object = new JSONObject();
for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
return object;
}
// nest a list of objects inside another
public static void putObjects( final JSONObject parentObject, final String key,
final JSONObject... objects ) {
List objectList = new ArrayList<JSONObject>();
for( JSONObject o : objects ) objectList.add( o );
parentObject.put( key, objectList );
}
Implementation example:
JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
buildObject(
new SimpleEntry( "child1Key1", "someValue" )
, new SimpleEntry( "child1Key2", "someValue" )
)
, buildObject(
new SimpleEntry( "child2Key1", "someValue" )
, new SimpleEntry( "child2Key2", "someValue" )
)
);
MYSQL 8.0:
Search my.ini
in disk, we will find this folder:
C:\ProgramData\MySQL\MySQL Server 8.0
It'sProgramData
, notProgram file
Data is in sub-folder: \Data
.
Each database
owns a folder, each table
is file, each index
is 1+ files.
Give an ID to uniquely identify the button, lets say myBtn
// when DOM is ready
$(document).ready(function () {
// Attach Button click event listener
$("#myBtn").click(function(){
// show Modal
$('#myModal').modal('show');
});
});
This is because keypress
events are fired before the new character is added to the value
of the element (so the first keypress
event is fired before the first character is added, while the value
is still empty). You should use keyup
instead, which is fired after the character has been added.
Note that, if your element #dSuggest
is the same as input:text[name=dSuggest]
you can simplify this code considerably (and if it isn't, having an element with a name that is the same as the id
of another element is not a good idea).
$('#dSuggest').keypress(function() {
var dInput = this.value;
console.log(dInput);
$(".dDimension:contains('" + dInput + "')").css("display","block");
});
Here is an alternative solution to @Terrance's answer. You can easly outsource the conversion. The Gson library does wonderful work converting various data structures into JSON and the other way around.
public static void execute() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("subject", "Using the GSON library");
comment.put("message", "Using libraries is convenient.");
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://192.168.0.1:3000/post/77/comments", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Similar can be done by using Jackson instead of Gson. I also recommend taking a look at Retrofit which hides a lot of this boilerplate code for you. For more experienced developers I recommend trying out RxAndroid.
Did you try vertical-align: middle ???
You can find more info on vertical-align here: http://www.w3schools.com/css/pr_pos_vertical-align.asp
There is a Date function.
Here is the function which will print all permutaion. This function implements logic Explained by peter.
public class Permutation
{
//http://www.java2s.com/Tutorial/Java/0100__Class-Definition/RecursivemethodtofindallpermutationsofaString.htm
public static void permuteString(String beginningString, String endingString)
{
if (endingString.Length <= 1)
Console.WriteLine(beginningString + endingString);
else
for (int i = 0; i < endingString.Length; i++)
{
String newString = endingString.Substring(0, i) + endingString.Substring(i + 1);
permuteString(beginningString + endingString.ElementAt(i), newString);
}
}
}
static void Main(string[] args)
{
Permutation.permuteString(String.Empty, "abc");
Console.ReadLine();
}
Use:
/category[@name='Sport' and author/text()[1]='James Small']
or use:
/category[@name='Sport' and author[starts-with(.,'James Small')]]
It is a good rule to try to avoid using the //
pseudo-operator whenever possible, because its evaluation can typically be very slow.
Also:
./somename
is equivalent to:
somename
so it is recommended to use the latter.