git gui provides this functionality under the diff view. Just right click the line(s) you're interested in and you should see a "stage this line to commit" menu item.
You can also check the default buffer size by calling the read only DEFAULT_BUFFER_SIZE attribute from io module.
import io
print (io.DEFAULT_BUFFER_SIZE)
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
The formula cited from wikipedia mentioned in the answers cannot be used to calculate normal probabilites. You would have to write a numerical integration approximation function using that formula in order to calculate the probability.
That formula computes the value for the probability density function. Since the normal distribution is continuous, you have to compute an integral to get probabilities. The wikipedia site mentions the CDF, which does not have a closed form for the normal distribution.
You can use key():
<?php
$array = array(
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4
);
while($element = current($array)) {
echo key($array)."\n";
next($array);
}
?>
It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore
file:
# intellij configs
.idea/
I was having an issue in my project where I was using ng-repeat track by $index but the products were not getting reflecting when data comes from database. My code is as below:
<div ng-repeat="product in productList.productList track by $index">
<product info="product"></product>
</div>
In the above code, product is a separate directive to display the product.But i came to know that $index causes issue when we pass data out from the scope. So the data losses and DOM can not be updated.
I found the solution by using product.id as a key in ng-repeat like below:
<div ng-repeat="product in productList.productList track by product.id">
<product info="product"></product>
</div>
But the above code again fails and throws the below error when more than one product comes with same id:
angular.js:11706 Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater
So finally i solved the problem by making dynamic unique key of ng-repeat like below:
<div ng-repeat="product in productList.productList track by (product.id + $index)">
<product info="product"></product>
</div>
This solved my problem and hope this will help you in future.
You will need have to download InternetExplorer driver executable on your system, download it from the source (http://code.google.com/p/selenium/downloads/list) after download unzip it and put on the place of somewhere in your computer. In my example, I will place it to D:\iexploredriver.exe
Then you have write below code in your eclipse main class
System.setProperty("webdriver.ie.driver", "D:/iexploredriver.exe");
WebDriver driver = new InternetExplorerDriver();
you should add plug in to your local setting of firefox in your user home
vladimir@shinsengumi ~/.mozilla/plugins $ pwd
/home/vladimir/.mozilla/plugins
vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
lrwxrwxrwx 1 vladimir vladimir 60 Jan 1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so
In my case the offset was added to a custom element with grid layout within an li while the ul was a vertical flexbox.
The pretty simple solution was to set the define the li as block element with
li {
display: block;
}
And the offset was gone
return numberString.TrimStart('0');
Have you try $ sudo ./catalina.sh stop
? It worked in my case.
New Table...
As mentioned by Seeker, the problem could have been that you setup the click()
function too soon. From your code snippet, we cannot know where you placed the script and whether it gets run at the right time.
An important point is to run such scripts after the document is ready. This is done by placing the click()
initialization within that other function as in:
jQuery(document).ready(function()
{
jQuery("body").click(function()
{
// ... your click code here ...
});
});
This is usually the best method, especially if you include your JavaScript code in your <head>
tag. If you include it at the very bottom of the page, then the ready()
function is less important, but it may still be useful.
$date = new DateTime(date("Y-m-d"));
$date->modify('+7 day');
$tomorrowDATE = $date->format('Y-m-d');
I had this problem with this kind of simple form:
public partial class MyForm : Form
{
public MyForm()
{
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(Object sender, EventArgs e)
{
InitializeComponent();
}
internal void UpdateLabel(string s)
{
Invoke(new Action(() => { label1.Text = s; }));
}
}
Then for n
other async threads I was using new MyForm().UpdateLabel(text)
to try and call the UI thread, but the constructor gives no handle to the UI thread instance, so other threads get other instance handles, which are either Object reference not set to an instance of an object
or Invoke or BeginInvoke cannot be called on a control until the window handle has been created
. To solve this I used a static object to hold the UI handle:
public partial class MyForm : Form
{
private static MyForm _mf;
public MyForm()
{
Load += new EventHandler(Form1_Load);
}
private void Form1_Load(Object sender, EventArgs e)
{
InitializeComponent();
_mf = this;
}
internal void UpdateLabel(string s)
{
_mf.Invoke((MethodInvoker) delegate { _mf.label1.Text = s; });
}
}
I guess it's working fine, so far...
My usecase was replacing None
with some default value.
I've timed approaches to this problem that were presented here, including the one by @kxr - using str.count
.
Test code in ipython with Python 3.8.1:
def rep1(lst, replacer = 0):
''' List comprehension, new list '''
return [item if item is not None else replacer for item in lst]
def rep2(lst, replacer = 0):
''' List comprehension, in-place '''
lst[:] = [item if item is not None else replacer for item in lst]
return lst
def rep3(lst, replacer = 0):
''' enumerate() with comparison - in-place '''
for idx, item in enumerate(lst):
if item is None:
lst[idx] = replacer
return lst
def rep4(lst, replacer = 0):
''' Using str.index + Exception, in-place '''
idx = -1
# none_amount = lst.count(None)
while True:
try:
idx = lst.index(None, idx+1)
except ValueError:
break
else:
lst[idx] = replacer
return lst
def rep5(lst, replacer = 0):
''' Using str.index + str.count, in-place '''
idx = -1
for _ in range(lst.count(None)):
idx = lst.index(None, idx+1)
lst[idx] = replacer
return lst
def rep6(lst, replacer = 0):
''' Using map, return map iterator '''
return map(lambda item: item if item is not None else replacer, lst)
def rep7(lst, replacer = 0):
''' Using map, return new list '''
return list(map(lambda item: item if item is not None else replacer, lst))
lst = [5]*10**6
# lst = [None]*10**6
%timeit rep1(lst)
%timeit rep2(lst)
%timeit rep3(lst)
%timeit rep4(lst)
%timeit rep5(lst)
%timeit rep6(lst)
%timeit rep7(lst)
I get:
26.3 ms ± 163 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
29.3 ms ± 206 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
33.8 ms ± 191 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
11.9 ms ± 37.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
11.9 ms ± 60.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
260 ns ± 1.84 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
56.5 ms ± 204 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Using the internal str.index
is in fact faster than any manual comparison.
I didn't know if the exception in test 4 would be more laborious than using str.count
, the difference seems negligible.
Note that map()
(test 6) returns an iterator and not an actual list, thus test 7.
Alternatively, you can use requests.Session
and observe cookies
before and after a request:
>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}
Here's a method using display:flex
:
.container {_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
display: flex;_x000D_
position: fixed;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>centered text!</div>_x000D_
</div>
_x000D_
I am a late comer, but maybe I can say this with a specific example:
Say, if you have a <table>
, with <tr>
, and then <td>
. Now, let's say you set 3 event handlers for the <td>
element, then if you do event.stopPropagation()
in the first event handler you set for <td>
, then all event handlers for <td>
will still run, but the event just won't propagate to <tr>
or <table>
(and won't go up and up to <body>
, <html>
, document
, and window
).
Now, however, if you use event.stopImmediatePropagation()
in your first event handler, then, the other two event handlers for <td>
WILL NOT run, and won't propagate up to <tr>
, <table>
(and won't go up and up to <body>
, <html>
, document
, and window
).
Note that it is not just for <td>
. For other elements, it will follow the same principle.
$('.date-pick').datePicker().val(new Date()).trigger('change')
finally, that what i look for the last few hours! I need initiate changes, not just setup date in text field!
On you fragment
((Name_of_your_Activity) getActivity()).helper
On Activity
DbHelper helper = new DbHelper(this);
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
I think the only way is by using internel PHP code like MANOJ and Fernando suggest.
curl post/get in php file on your server --> call this php file with ajax
The PHP file let say (fb.php):
$commentdata=$_GET['commentdata'];
$fbUrl="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";
curl_setopt($ch, CURLOPT_URL,$fbUrl);
curl_setopt($ch, CURLOPT_POST, 1);
// POST data here
curl_setopt($ch, CURLOPT_POSTFIELDS,
"message=".$commentdata);
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
echo $server_output;
curl_close ($ch);
Than use AJAX GET to
fb.php?commentmeta=your comment goes here
from your server.
Or do this with simple HTML and JavaScript from externel server:
Message: <input type="text" id="message">
<input type="submit" onclick='PostMessage()'>
<script>
function PostMessage() {
var comment = document.getElementById('message').value;
window.location.assign('http://yourdomain.tld/fb.php?commentmeta='+comment)
}
</script>
You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.
>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])
>>> A
array([[1, 2, 0],
[0, 0, 3],
[1, 0, 4]])
>>> sA = sparse.csr_matrix(A) # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)
>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
with 5 stored elements in Compressed Sparse Row format>
>>> print sA
(0, 0) 1
(0, 1) 2
(1, 2) 3
(2, 0) 1
(2, 2) 4
If you are using Entity Framework 5 < you can use DbGeography
. Example from MSDN:
public class University
{
public int UniversityID { get; set; }
public string Name { get; set; }
public DbGeography Location { get; set; }
}
public partial class UniversityContext : DbContext
{
public DbSet<University> Universities { get; set; }
}
using (var context = new UniversityContext ())
{
context.Universities.Add(new University()
{
Name = "Graphic Design Institute",
Location = DbGeography.FromText("POINT(-122.336106 47.605049)"),
});
context. Universities.Add(new University()
{
Name = "School of Fine Art",
Location = DbGeography.FromText("POINT(-122.335197 47.646711)"),
});
context.SaveChanges();
var myLocation = DbGeography.FromText("POINT(-122.296623 47.640405)");
var university = (from u in context.Universities
orderby u.Location.Distance(myLocation)
select u).FirstOrDefault();
Console.WriteLine(
"The closest University to you is: {0}.",
university.Name);
}
https://msdn.microsoft.com/en-us/library/hh859721(v=vs.113).aspx
Something I struggled with then I started using DbGeography
was the coordinateSystemId
. See the answer below for an excellent explanation and source for the code below.
public class GeoHelper
{
public const int SridGoogleMaps = 4326;
public const int SridCustomMap = 3857;
public static DbGeography FromLatLng(double lat, double lng)
{
return DbGeography.PointFromText(
"POINT("
+ lng.ToString() + " "
+ lat.ToString() + ")",
SridGoogleMaps);
}
}
Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).
Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):
SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC
This will give you the SSN with the highest total time and the total time for it.
Edit - If you have multiple with an equal time and want them all you would use:
SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))
Have you tried https://www.virtualbox.org/manual/ch04.html which has step-by-step instructions to help you?
Try echo_read_request_body.
"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."
location /log {
log_format postdata $request_body;
access_log /mnt/logs/nginx/my_tracking.access.log postdata;
echo_read_request_body;
}
There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines()
, eg) for use.
I am using this Temporary Solution:
import {Pipe, PipeTransform} from "angular2/core";
import {DateFormatter} from 'angular2/src/facade/intl';
@Pipe({
name: 'dateFormat'
})
export class DateFormat implements PipeTransform {
transform(value: any, args: string[]): any {
if (value) {
var date = value instanceof Date ? value : new Date(value);
return DateFormatter.format(date, 'pt', 'dd/MM/yyyy');
}
}
}
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("C:\\");
}
}
If your application needs cmd arguments, use something like this:
using System.Diagnostics;
class Program
{
static void Main()
{
LaunchCommandLineApp();
}
/// <summary>
/// Launch the application with some options set.
/// </summary>
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// Log error.
}
}
}
you could also do show columns in $table
or see Hive, how do I retrieve all the database's tables columns for access to hive metadata
Concise if you are just interested in the time elapsed that is under 24 hours. You can format the output as needed in the return statement :
import datetime
def elapsed_interval(start,end):
elapsed = end - start
min,secs=divmod(elapsed.days * 86400 + elapsed.seconds, 60)
hour, minutes = divmod(min, 60)
return '%.2d:%.2d:%.2d' % (hour,minutes,secs)
if __name__ == '__main__':
time_start=datetime.datetime.now()
""" do your process """
time_end=datetime.datetime.now()
total_time=elapsed_interval(time_start,time_end)
Most programs will check the $EDITOR
environment variable, so you can set that to the path of TextEdit in your bashrc. Git will use this as well.
~/.bashrc
file:export EDITOR="/Applications/TextEdit.app/Contents/MacOS/TextEdit"
echo "export EDITOR=\"/Applications/TextEdit.app/Contents/MacOS/TextEdit\"" >> ~/.bashrc
If you are using zsh, use ~/.zshrc
instead of ~/.bashrc
.
If you are using at least Java 8 you can use method runAsync
from class CompletableFuture
CompletableFuture.runAsync(() -> {...});
If you need to return a result use supplyAsync
instead
CompletableFuture.supplyAsync(() -> 1);
I have found that the simplest way to do this is to set onClick for each button in the xml
<Button
android:id="@+id/vrHelp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/ic_menu_help"
android:onClick="helpB" />
and then you can do a switch case like this
public void helpB(View v) {
Button clickedButton = (Button) v;
switch (clickedButton.getId()) {
case R.id.vrHelp:
dosomething...
break;
case R.id.coHelp:
dosomething...
break;
case R.id.ksHelp:
dosomething...
break;
case R.id.uHelp:
dosomething...
break;
case R.id.pHelp:
dosomething...
break;
}
}
My Moving Average function, without numpy function:
from __future__ import division # must be on first line of script
class Solution:
def Moving_Avg(self,A):
m = A[0]
B = []
B.append(m)
for i in range(1,len(A)):
m = (m * i + A[i])/(i+1)
B.append(m)
return B
Performance wise substring(0, 1)
is better as found by following:
String example = "something";
String firstLetter = "";
long l=System.nanoTime();
firstLetter = String.valueOf(example.charAt(0));
System.out.println("String.valueOf: "+ (System.nanoTime()-l));
l=System.nanoTime();
firstLetter = Character.toString(example.charAt(0));
System.out.println("Character.toString: "+ (System.nanoTime()-l));
l=System.nanoTime();
firstLetter = example.substring(0, 1);
System.out.println("substring: "+ (System.nanoTime()-l));
Output:
String.valueOf: 38553
Character.toString: 30451
substring: 8660
try to change your build.gradle with these value:
android { compileSdkVersion 18 buildToolsVersion '21.0.1'
defaultConfig {
minSdkVersion 18
targetSdkVersion 18
}
I agree with the answer by Kenny Eliasson. Go with Extension methods. Here is a brief overview of extension methods and your required IfNotNull method.
Use .ashx file type and use the same code
what is the way to retrieve a Date object so that its always in GMT?
Instant.now()
You are using troublesome confusing old date-time classes that are now supplanted by the java.time classes.
Instant
= UTCThe Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Current moment in UTC.
To exchange this data as text, use the standard ISO 8601 formats exclusively. These formats are sensibly designed to be unambiguous, easy to process by machine, and easy to read across many cultures by people.
The java.time classes use the standard formats by default when parsing and generating strings.
String output = instant.toString() ;
2017-01-23T12:34:56.123456789Z
If you want to see that same moment as presented in the wall-clock time of a particular region, apply a ZoneId
to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Asia/Singapore" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same simultaneous moment, same point on the timeline.
See this code live at IdeOne.com.
Notice the eight hour difference, as the time zone of Asia/Singapore
currently has an offset-from-UTC of +08:00. Same moment, different wall-clock time.
instant.toString(): 2017-01-23T12:34:56.123456789Z
zdt.toString(): 2017-01-23T20:34:56.123456789+08:00[Asia/Singapore]
Avoid the legacy java.util.Date
class. But if you must, you can convert. Look to new methods added to the old classes.
java.util.Date date = Date.from( instant ) ;
…going the other way…
Instant instant = myJavaUtilDate.toInstant() ;
For date-only, use LocalDate
.
LocalDate ld = zdt.toLocalDate() ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
File.WriteAllText(file,content)
create write close
File.WriteAllBytes-- type binary
:)
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable
Type in command line
echo %JAVA_HOME%
and
java -version
To verify whether your installation was done successfully.
This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.
Steps to resolve:
Open the Run window:
Press windows+R
Open registry window:
Type regedit
and enter.
Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\
If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.
For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:
Create a new subkey of 1.8.
For 1.8 create a String Key with name JavaHome with the value of JRE home:
Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html
You have to put the python path in the PATH
variable.
In the System Variables section, you should have User Variables and System Variables. Search for the PATH
variable and edit its value, adding at the end ;C:\python27
.
The ;
is to tell the variable to add a new path to this value, and the rest, is just to tell which path that is.
On the other hand, you can use ;%python%
to add the variable you created.
You should use .keydown()
because .keypress()
will ignore "Arrows", for catching the key type use e.which
Press the result screen to focus (bottom right on fiddle screen) and then press arrow keys to see it work.
Notes:
.keypress()
will never be fired with Shift, Esc, and Delete but .keydown()
will..keypress()
in some browser will be triggered by arrow keys but its not cross-browser so its more reliable to use .keydown()
.More useful information
.which
Or .keyCode
of the event object - Some browsers won't support one of them but when using jQuery its safe to use the both since jQuery standardizes things. (I prefer .which
never had a problem with).ctrl | alt | shift | META
press with the actual captured key you should check the following properties of the event object - They will be set to TRUE if they were pressed:
event.ctrlKey
- ctrl event.altKey
- altevent.shiftKey
- shiftevent.metaKey
- META ( Command ? OR Windows Key )Finally - here are some useful key codes ( For a full list - keycode-cheatsheet ):
On unix I got that error when using the ~
shortcut for the user directory.
Changing it to /home/user
resolved the error.
It's easier to use only one code block, then you only need one redirection.
(
echo Line1
echo Line2
...
echo Last Line
) > filename.txt
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
Installing through distributed JDK DMG from the Oracle site auto-updates everything for me. I have seen (in El Capitan) updating through System Preferences > Java
do updates but that do not reflect to command line. Installing through DMG does the job.
I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands
OP, you can convert a string to type Boolean
by using any of the methods stated below:
string sample = "True";
bool myBool = bool.Parse(sample);
///or
bool myBool = Convert.ToBoolean(sample);
bool.Parse
expects one parameter which in this case is sample
, .ToBoolean
also expects one parameter.
You can use TryParse
which is the same as Parse
but it doesn't throw any exception :)
string sample = "false";
Boolean myBool;
if (Boolean.TryParse(sample , out myBool))
{
}
Please note that you cannot convert any type of string to type Boolean
because the value of a Boolean
can only be True
or False
Hope you understand :)
CSS
select.inpSelect {
//Remove original arrows
-webkit-appearance: none;
//Use png at assets/selectArrow.png for the arrow on the right
//Set the background color to a BadAss Green color
background: url(assets/selectArrow.png) no-repeat right #BADA55;
}
For beginning of month to month calculation:
from datetime import timedelta
from dateutil.relativedelta import relativedelta
end_date = start_date + relativedelta(months=delta_period) + timedelta(days=-delta_period)
Something like:
$qb = $entityManager->createQueryBuilder();
$qb->select('count(account.id)');
$qb->from('ZaysoCoreBundle:Account','account');
$count = $qb->getQuery()->getSingleScalarResult();
Some folks feel that expressions are somehow better than just using straight DQL. One even went so far as to edit a four year old answer. I rolled his edit back. Go figure.
NSDateFormatter *df= [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *dt1 = [[NSDate alloc] init];
NSDate *dt2 = [[NSDate alloc] init];
dt1=[df dateFromString:@"2011-02-25"];
dt2=[df dateFromString:@"2011-03-25"];
NSComparisonResult result = [dt1 compare:dt2];
switch (result)
{
case NSOrderedAscending: NSLog(@"%@ is greater than %@", dt2, dt1); break;
case NSOrderedDescending: NSLog(@"%@ is less %@", dt2, dt1); break;
case NSOrderedSame: NSLog(@"%@ is equal to %@", dt2, dt1); break;
default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
}
Enjoy coding......
I don't know this off the top of my head, but look in the file which shows the user's name, etc in the header of the page after the user has logged in. It might help if you turned on template hints (see this tutorial.
When you find the line such as "Hello <? //code for showing username?>"
, just copy that line and show it where you need to
If you need to find database objects (e.g. tables, columns, triggers) by name - have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).
It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??
It is possible to scaffold a view. Just use -Tables the way you would to scaffold a table, only use the name of your view. E.g., If the name of your view is ‘vw_inventory’, then run this command in the Package Manager Console (substituting your own information for "My..."):
PM> Scaffold-DbContext "Server=MyServer;Database=MyDatabase;user id=MyUserId;password=MyPassword" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Temp -Tables vw_inventory
This command will create a model file and context file in the Temp directory of your project. You can move the model file into your models directory (remember to change the namespace name). You can copy what you need from the context file and paste it into the appropriate existing context file in your project.
Note: If you want to use your view in an integration test using a local db, you'll need to create the view as part of your db setup. If you’re going to use the view in more than one test, make sure to add a check for existence of the view. In this case, since the SQL ‘Create View’ statement is required to be the only statement in the batch, you’ll need to run the create view as dynamic Sql within the existence check statement. Alternatively you could run separate ‘if exists drop view…’, then ‘create view’ statements, but if multiple tests are running concurrently, you don’t want the view to be dropped if another test is using it. Example:
void setupDb() {
...
SomeDb.Command(db => db.Database.ExecuteSqlRaw(CreateInventoryView()));
...
}
public string CreateInventoryView() => @"
IF OBJECT_ID('[dbo].[vw_inventory]') IS NULL
BEGIN EXEC('CREATE VIEW [dbo].[vw_inventory] AS
SELECT ...')
END";
CSS
ol {
margin: 0 0 1.5em;
padding: 0;
counter-reset: item;
}
ol > li {
margin: 0;
padding: 0 0 0 2em;
text-indent: -2em;
list-style-type: none;
counter-increment: item;
}
ol > li:before {
display: inline-block;
width: 1em;
padding-right: 0.5em;
font-weight: bold;
text-align: right;
content: counter(item) ".";
}
I had the same problem.
.gitmodules
had the submodule, but after a git submodule init
command it wasn't in .git/config
.
Turns out the developer who added the submodule also added the submodule directory to the .gitignore
file. That doesn't work.
The apiKey in this configuration snippet just identifies your Firebase project on the Google servers. It is not a security risk for someone to know it. In fact, it is necessary for them to know it, in order for them to interact with your Firebase project. This same configuration data is also included in every iOS and Android app that uses Firebase as its backend.
In that sense it is very similar to the database URL that identifies the back-end database associated with your project in the same snippet: https://<app-id>.firebaseio.com
. See this question on why this is not a security risk: How to restrict Firebase data modification?, including the use of Firebase's server side security rules to ensure only authorized users can access the backend services.
If you want to learn how to secure all data access to your Firebase backend services is authorized, read up on the documentation on Firebase security rules. These rules control access to file storage and database access, and are enforced on the Firebase servers. So no matter if it's your code, or somebody else's code that uses you configuration data, it can only do what the security rules allow it to do.
For another explanation of what Firebase uses these values for, and for which of them you can set quotas, see the Firebase documentation on using and managing API keys.
If you'd like to reduce the risk of committing this configuration data to version control, consider using the SDK auto-configuration of Firebase Hosting. While the keys will still end up in the browser in the same format, they won't be hard-coded into your code anymore with that.
The problem is that you are trying to access a collection in an object that is detached. You need to re-attach the object before accessing the collection to the current session. You can do that through
session.update(object);
Using lazy=false
is not a good solution because you are throwing away the Lazy Initialization feature of hibernate. When lazy=false
, the collection is loaded in memory at the same time that the object is requested. This means that if we have a collection with 1000 items, they all will be loaded in memory, despite we are going to access them or not. And this is not good.
Please read this article where it explains the problem, the possible solutions and why is implemented this way. Also, to understand Sessions and Transactions you must read this other article.
If you're using an IntelliJ editor such as WebStorm, PyCharm, RubyMine, or IntelliJ IDEA:
In the Environments section of File/Settings/JavaScript/Code Quality Tools/JSHint, click on the jQuery checkbox.
It is what you do inside the loop that affects perfomance, not the actual looping construct (assuming your case is non-trivial).
.NET Core will install and run on macOS - and just about any other desktop OS.
IDEs are available for the mac, including:
Mono is a good option that I've used in the past. But with Core 3.0 out now, I would go that route.
const express = require('express');_x000D_
let app = express();_x000D_
app.use(express.json());
_x000D_
This app.use(express.json) will now let you read the incoming post JSON object
Javascript may be hooking up to the click-event of the anchor, rather than injecting any href.
For example, jQuery:
$('a.view').click(function() { Alert('anchor without a href was clicked');});
Of course, the javascript can do anything it wants with the click event--such as navigate to some other page (in which case the href is never set, but the anchor still behaves as though it were)
There's not really a good way to do this, usually you see an extra item in the enum, i.e.
enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};
So then you can do:
int fuz[FOOBAR_NR_ITEMS];
Still not very nice though.
But of course you do realize that just the number of items in an enum is not safe, given e.g.
enum foobar {foo, bar = 5, baz, quz = 20};
the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.
edit: as requested, made the special entry stick out more.
conn.exec = <<eos
select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from table1, table2, table3, etc, etc, etc, etc, etc,
where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos
I was stuck in same problem for many hours. I tried everything found on internet.
At last, I figured out a surprising solution : I had missed \SQLEXPRESS
part of the Server name: MY-COMPUTER-NAME\SQLEXPRESS
I hope this helps someone who is stuck in similar kind of problem.
For using Google SignIn in Android app, you need
google-services.json
which you can generate using the instruction mentioned here
I was getting the exact same problem with no chnges to the code base or servers. It turned out to be that the DB server was running at 100% CPU and SQL Server was being starved of any CPU time, which caused the timeout.
Instead of the *
selector you can use the :not(selector)
with the >
selector and set something that definitely wont be a child.
Edit: I thought it would be faster but it turns out I was wrong. Disregard.
Example:
.container > :not(marquee){
color:red;
}
<div class="container">
<p></p>
<span></span>
<div>
This is what I did for the instagram API. converted timestamp with date method by multiplying by 1000. and then added all entity individually like (year, months, etc)
created the custom month list name and mapped with getMonth()
method which returns the index of the month.
convertStampDate(unixtimestamp){
// Unixtimestamp
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// filtered fate
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and thats it.
With RHEL 7 / CentOS 7, firewalld was introduced to manage iptables. IMHO, firewalld is more suited for workstations than for server environments.
It is possible to go back to a more classic iptables setup. First, stop and mask the firewalld service:
systemctl stop firewalld
systemctl mask firewalld
Then, install the iptables-services package:
yum install iptables-services
Enable the service at boot-time:
systemctl enable iptables
Managing the service
systemctl [stop|start|restart] iptables
Saving your firewall rules can be done as follows:
service iptables save
or
/usr/libexec/iptables/iptables.init save
I think the easiest way to match the characters like
\^$.?*|+()[
are using character classes from within R. Consider the following to clean column headers from a data file, which could contain spaces, and punctuation characters:
> library(stringr)
> colnames(order_table) <- str_replace_all(colnames(order_table),"[:punct:]|[:space:]","")
This approach allows us to string character classes to match punctation characters, in addition to whitespace characters, something you would normally have to escape with \\
to detect. You can learn more about the character classes at this cheatsheet below, and you can also type in ?regexp
to see more info about this.
https://www.rstudio.com/wp-content/uploads/2016/09/RegExCheatsheet.pdf
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.
If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!
Making @sulai suggestion more generic :
@TargetApi(Build.VERSION_CODES.HONEYCOMB) // API 11
public static <T> void executeAsyncTask(AsyncTask<T, ?, ?> asyncTask, T... params) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
else
asyncTask.execute(params);
}
just saw this now, if you are working with a list of object you can try this
public class user
{
public string username { get; set; }
public string password { get; set; }
}
List<user> userlist = new List<user>();
userlist.Add(new user { username = "macbruno", password = "1234" });
userlist.Add(new user { username = "james", password = "5678" });
string myusername = "james";
string mypassword = "23432";
user theUser = userlist.Find(
delegate (user thisuser)
{
return thisuser.username== myusername && thisuser.password == mypassword;
}
);
if (theUser != null)
{
Dosomething();
}
else
{
DoSomethingElse();
}
When you run the Windows Command Prompt, and type in python
, it starts the Python interpreter.
Typing it again tries to interpret python
as a variable, which doesn't exist and thus won't work:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line
C:\Users\USER>
If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python
is interpreted as a variable, which you have not defined.
None of the previous answers worked for me. I called the postback of the button on the OnOkScript event.
<div>
<cc1:ModalPopupExtender PopupControlID="Panel1"
ID="ModalPopupExtender1"
runat="server" TargetControlID="LinkButton1" OkControlID="Ok"
OnOkScript="__doPostBack('Ok','')">
</cc1:ModalPopupExtender>
<asp:LinkButton ID="LinkButton1" runat="server">LinkButton</asp:LinkButton>
</div>
<asp:Panel ID="Panel1" runat="server">
<asp:Button ID="Ok" runat="server" Text="Ok" onclick="Ok_Click" />
</asp:Panel>
Its depends on your locale system time settings, make 24 hours then it will show you 24 hours time.
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
You could delete your .htaceess file and let the system creates a new (blank or basic) one. It may be that some lines you added are incorrect statements, or something else inside is causing the problem. You can then add line by line from your old .htaccess file to see what caused the problem.
That worked for me. The lines telling machine not to display php extensions were problem in my case (RewriteCond and RewriteRule). My old .htaccess file worked just fine on a shared server, but this issue appeared when I switched to VPS.
Math.floor(Math.random() * (limit+1))
Math.random()
generates a floating point number between 0 and 1, Math.floor()
rounds it down to an integer.
By multiplying it by a number, you effectively make the range 0..number-1
. If you wish to generate it in range from num1
to num2
, do:
Math.floor(Math.random() * (num2-num1 + 1) + num1)
To generate more numbers, just use a for loop and put results into an array or write them into the document directly.
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
I usualy use <li>
to include <a>
link. I disabled click action writing like this;
You may not include <a>
link, then you will ignore my post.
a.noclick {_x000D_
pointer-events: none;_x000D_
}
_x000D_
<a class="noclick" href="#">this is disabled</a>
_x000D_
For Node/Express developers you can use middleware and set this via server.
app.use(function(req, res, next) {
res.setHeader('X-UA-Compatible', 'IE=edge');
next();
});
The workaround is to export the collection as explained in other answers or references. This will export all requests in that collection to JSON file.
Then edit the JSON file to remove the requests you do not want using any editor; this is very simple.
Look for "item"
collection in file. This contains all your requests; one in each item. Remove the items you do not want to keep.
If you import this edited file in Postman where original collection already exists, Postman will ask you if you want to replace it or create a copy. If you want to avoid this, you may consider changing "_postman_id"
and "name"
under "info"
. If original collection will not exist while importing edited collection, then this change is not needed.
The code below imports the Python script given by it's path, no matter where it is located, in a Python version-save way:
def import_module_by_path(path):
name = os.path.splitext(os.path.basename(path))[0]
if sys.version_info[0] == 2:
# Python 2
import imp
return imp.load_source(name, path)
elif sys.version_info[:2] <= (3, 4):
# Python 3, version <= 3.4
from importlib.machinery import SourceFileLoader
return SourceFileLoader(name, path).load_module()
else:
# Python 3, after 3.4
import importlib.util
spec = importlib.util.spec_from_file_location(name, path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
This code is not written by me; I found it in the codebase of psutils, in psutils.test.__init__.py
(line 1042; permalink to most recent commit as of 09.10.2020).
Usage example:
script = "/home/username/Documents/some_script.py"
some_module = import_module_by_path(script)
print(some_module.foo())
Caveat: The module will be treated as top-level. If it's a submodule of some bigger project, then relative imports from parent packages will fail.
Add this code inside your input tag
<?php if ($tag_1 == 'yes') echo "checked='checked'"; ?>
You need to clear the OnCheckedChangeListener
before setting setChecked()
:
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mRadioButton.setOnCheckedChangeListener(null);
holder.mRadioButton.setChecked(position == mCheckedPosition);
holder.mRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckedPosition = position;
notifyDataSetChanged();
}
});
}
This way it won't trigger the java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
error.
You can also use wget to »untar it inline«. Simply specify stdout as the output file (-O -
):
wget --no-check-certificate https://github.com/pinard/Pymacs/tarball/v0.24-beta2 -O - | tar xz
On Windows 7 I solved this by going into my environment settings (try this link for how) and adding user variables http_proxy
and https_proxy
with my proxy details.
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
_x000D_
#yourElement {
margin-left: 10px;
}
_x000D_
<div id="yourElement"></div>
_x000D_
<select ng-model="option" ng-options="o for o in options">
$scope.option will be equal to 'var1' after change, even you see value="0" in generated html
Following could be one of ways:
dataframe = dataframe.sample(frac=1, random_state=42).reset_index(drop=True)
where
frac=1 means all rows of a dataframe
random_state=42 means keeping same order in each execution
reset_index(drop=True) means reinitialize index for randomized dataframe
You are mixing razor and aspx syntax,if your view engine is razor just do this:
<button class="btn btn-info" type="button" id="addressSearch"
onclick="location.href='@Url.Action("List", "Search")'">
Disclosure: I wrote FieldVal.
Here is a solution using FieldVal. By using FieldVal UI to build a form and then FieldVal to validate the input, you can pass the error straight back into the form.
You can even run the validation code on the backend (if you're using Node.js) and show the error in the form without wiring all of the fields up manually.
Live demo: http://codepen.io/MarcusLongmuir/pen/WbOydx
function validate_form(data) {
// This would work on the back end too (if you're using Node)
// Validate the provided data
var validator = new FieldVal(data);
validator.get("email", BasicVal.email(true));
validator.get("title", BasicVal.string(true));
validator.get("url", BasicVal.url(true));
return validator.end();
}
$(document).ready(function(){
// Create a form and add some fields
var form = new FVForm()
.add_field("email", new FVTextField("Email"))
.add_field("title", new FVTextField("Title"))
.add_field("url", new FVTextField("URL"))
.on_submit(function(value){
// Clear the existing errors
form.clear_errors();
// Use the function above to validate the input
var error = validate_form(value);
if (error) {
// Pass the error into the form
form.error(error);
} else {
// Use the data here
alert(JSON.stringify(value));
}
})
form.element.append(
$("<button/>").text("Submit")
).appendTo("body");
//Pre-populate the form
form.val({
"email": "[email protected]",
"title": "Your Title",
"url": "http://www.example.com"
})
});
The div take the height of its parent, but since it has no content (expecpt for your divs) it will only be as height as its content.
You need to set the height of the body and html:
HTML:
<div class="block12">
<div class="block1">1</div>
<div class="block2">2</div>
</div>
<div class="block3">3</div>
CSS:
body, html {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.block12 {
width: 100%;
height: 50%;
background: yellow;
overflow: auto;
}
.block1, .block2 {
width: 50%;
height: 100%;
display: inline-block;
margin-right: -4px;
background: lightgreen;
}
.block2 { background: lightgray }
.block3 {
width: 100%;
height: 50%;
background: lightblue;
}
And a JSFiddle
You can use simple way for genarate RSA . Use rsa library
pip install rsa
This smells of something that should be done with a JOIN instead. Can you share the larger problem with us?
Hey, I should be able to get this down to a single statement, but I haven't had time to play with it further yet today and may not get to. In the mean-time, know that you should be able to edit the query for your inner cursor to create the row numbers as part of the query using the ROW_NUMBER() function. From there, you can fold the inner cursor into the outer by doing an INNER JOIN on it (you can join on a sub query). Finally, any SELECT statement can be converted to an UPDATE using this method:
UPDATE [YourTable/Alias]
SET [Column] = q.Value
FROM
(
... complicate select query here ...
) q
Where [YourTable/Alias]
is a table or alias used in the select query.
From a button in view call .click(call some java script). From there call controller method by window.location.href = 'Controller/Method';
In controller either do the database call and get the datatable or call some method get the data from database table to a datatable and then do following,
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport"+DateTime.Now+".csv");
Response.Charset = "";
//Response.ContentType = "application/text";
Response.ContentType = "application/x-msexcel";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
You could try the subplot_tool()
plt.subplot_tool()
There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.
Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.
import Tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")
frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")
root.mainloop()
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
Follow the below code.
Add this to your TS file.
declare this, top of your class.
declare var google;
declare the view child for Map and the input.
@ViewChild('mapElement', {static: true}) mapNativeElement: ElementRef;
@ViewChild('autoCompleteInput', {static: true}) inputNativeElement: any;
this method is run on ngOnInit() event or ngAfterViewInit() event.
autoComplete() {
const map = new google.maps.Map(this.mapNativeElement.nativeElement, {
center: {lat: -33.8688, lng: 151.2093},
zoom: 7
});
const infowindow = new google.maps.InfoWindow();
const infowindowContent = document.getElementById('infowindow-content');
infowindow.setContent(infowindowContent);
const marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
const autocomplete = new google.maps.places.Autocomplete(this.inputNativeElement.nativeElement as HTMLInputElement);
autocomplete.addListener('place_changed', () => {
infowindow.close();
marker.setVisible(false);
const place = autocomplete.getPlace();
let cus_location = {
lat: place.geometry.location.lat(),
long: place.geometry.location.lng()
}
console.log('place data :................', cus_location);
localStorage.setItem('LOC_DATA', this.helper.encryptData(cus_location));
if (!place.geometry) {
// User entered the name of a Place that was not suggested and
// pressed the Enter key, or the Place Details request failed.
window.alert('No details available for input: ' + place.name );
return;
}
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
marker.setPosition(place.geometry.location);
marker.setVisible(true);
let address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
if(infowindowContent){
infowindowContent.children['place-icon'].src = place.icon;
infowindowContent.children['place-name'].textContent = place.name;
infowindowContent.children['place-address'].textContent = address;
}
infowindow.open(map, marker);
});
}
calling the method on ngAfterViewInit.
ngAfterViewInit(): void {
this.autoComplete();
}
And this is the HTML code. please modify as per your need.
<ion-content fullscreen>
<div class="location-col">
<div class="google-map">
<!-- <img src="../../assets/images/google-map.jpg" alt=""> -->
<div #mapElement id="map"></div>
</div>
<div class="location-info">
<h2>Where is your car located?</h2>
<p>Enter address manually or click location detector icon to use current address.</p>
<div class="form-group">
<div class="location-row">
<input type="text" #autoCompleteInput class="location-input" [(ngModel)]="search_location" placeholder="Search location">
<span class="location-icon" (click)="getCurrentLocation()">
<img src="../../assets/images/location-icon.svg" alt="">
</span>
</div>
<button type="button" class="location-search-btn" (click)="goToVendorSearch()">
<i class="fa fa-angle-right"></i>
</button>
</div>
</div>
</div>
</ion-content>
here is how I did it in jquery:
jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});
A quick way is to use python command line tool.
Simply type import <your module name>
You see an error if module is missing.
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>>> import sys
>>> import jocker
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named jocker
$
It's working now. I had to restart server. Thanks
If you want a fragment solution, I have made a fork of android-color-picker where DialogFragment is used and is re-created on configuration change. Here's the link: https://github.com/lomza/android-color-picker
This might be helpful
http://opencvuser.blogspot.in/2011/08/creating-haar-cascade-classifier-aka.html
The proper way that actually works:
URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();
It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.
(The seemingly obvious new File(resource.getPath())
doesn't work for all paths! The path is still URL-encoded!)
{
"number" : ["1","2","3"],
"alphabet" : ["a", "b", "c"]
}
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
Seems that you need classmethod:
class World(object):
allAirports = []
@classmethod
def initialize(cls):
if not cls.allAirports:
f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
file_reader = csv.reader(f)
for col in file_reader:
cls.allAirports.append(Airport(col[0],col[2],col[3]))
return cls.allAirports
Something like:
find /path/ -type f -exec stat \{} --printf="%y\n" \; |
sort -n -r |
head -n 1
Explanation:
try this scp -r -P2222 [email protected]:/home2/kwazy/www/utrecht-connected.nl /Desktop
Another easier option if you're going to be pulling files left and right is to just use an SFTP client like WinSCP. Then you're not typing out 100 characters every time you want to pull something, just drag and drop.
Edit: Just noticed /Desktop probably isn't where you're looking to download the file to. Should be something like C:\Users\you\Desktop
Agile is not a methodology, embracing the agile manifesto means adopting a particular philosophy about software development. Within that philosophical perspective, there are many processes and practices. Scrum is a set of practices that follow agile principles. Many people grab onto the practices and processes without embracing (or even understanding) the underlying philosophy and they often end up with gorillarinas.
new File(path).toURI().toURL();
you can do this without jQuery:
var form=document.getElementById('form-id');//retrieve the form as a DOM element
var input = document.createElement('input');//prepare a new input DOM element
input.setAttribute('name', inputName);//set the param name
input.setAttribute('value', inputValue);//set the value
input.setAttribute('type', inputType)//set the type, like "hidden" or other
form.appendChild(input);//append the input to the form
form.submit();//send with added input
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
In my case, the error disappeared after I rebooted my OS and restarted MariaDB-server. Strange.
A memory heap is a location in memory where memory may be allocated at random access.
Unlike the stack where memory is allocated and released in a very defined order, individual data elements allocated on the heap are typically released in ways which is asynchronous from one another. Any such data element is freed when the program explicitly releases the corresponding pointer, and this may result in a fragmented heap. In opposition only data at the top (or the bottom, depending on the way the stack works) may be released, resulting in data element being freed in the reverse order they were allocated.
This works for me, angular 9:
component.html file:
<mat-checkbox (change)="checkValue($event)">text</mat-checkbox>
component.ts file:
checkValue(e){console.log(e.target.checked)}
to insert a new column at a given location (0 <= loc <= amount of columns) in a data frame, just use Dataframe.insert:
DataFrame.insert(loc, column, value)
Therefore, if you want to add the column e at the end of a data frame called df, you can use:
e = [-0.335485, -1.166658, -0.385571]
DataFrame.insert(loc=len(df.columns), column='e', value=e)
value can be a Series, an integer (in which case all cells get filled with this one value), or an array-like structure
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html
Follow these steps to fix this it looks too long but trust me it won't take more than 5 minutes:
Step-1: Create two ssh key pairs:
ssh-keygen -t rsa -C "[email protected]"
Step-2: It will create two ssh keys here:
~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2
Step-3: Now we need to add these keys:
ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
- You can see the added keys list by using this command:
ssh-add -l
- You can remove old cached keys by this command:
ssh-add -D
Step-4: Modify the ssh config
cd ~/.ssh/
touch config
subl -a config
or code config
or nano config
Step-5: Add this to config file:
#Github account1
Host github.com-account1
HostName github.com
User account1
IdentityFile ~/.ssh/id_rsa_account1
#Github account2
Host github.com-account2
HostName github.com
User account2
IdentityFile ~/.ssh/id_rsa_account2
Step-6: Update your .git/config
file:
Step-6.1: Navigate to account1's project and update host:
[remote "origin"]
url = [email protected]:account1/gfs.git
If you are invited by some other user in their git Repository. Then you need to update the host like this:
[remote "origin"]
url = [email protected]:invitedByUserName/gfs.git
Step-6.2: Navigate to account2's project and update host:
[remote "origin"]
url = [email protected]:account2/gfs.git
Step-7: Update user name and email for each repository separately if required this is not an amendatory step:
Navigate to account1 project and run these:
git config user.name "account1"
git config user.email "[email protected]"
Navigate to account2 project and run these:
git config user.name "account2"
git config user.email "[email protected]"
The way I usually do it is subtracting the two DateTime and this gets me a TimeSpan that will tell me the diff.
Here's an example:
DateTime start = DateTime.Now;
// Do some work
TimeSpan timeDiff = DateTime.Now - start;
timeDiff.TotalMilliseconds;
I had this problem because my entitlements file was malformed due to previous manual editing. I removed the wrongly formatted entitlement entry syntax and then i could click "fix" in the capabilities tab and Xcode added the entitlement to my file.
Here is an example of a properly formatted entitlements file ("Runner.entitlements
"):
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>aps-environment</key>
<string>development</string>
<key>com.apple.developer.applesignin</key>
<array>
<string>Default</string>
</array>
</dict>
</plist>
You want the zip
function.
for (f,b) in zip(foo, bar):
print "f: ", f ,"; b: ", b
You can use:
((count = FIRSTV - SECONDV))
to avoid invoking a separate process, as per the following transcript:
pax:~$ FIRSTV=7
pax:~$ SECONDV=2
pax:~$ ((count = FIRSTV - SECONDV))
pax:~$ echo $count
5
Use
$ java -XshowSettings
Property settings:
java.home = /home/nisar/javadev/javasuncom/jdk1.7.0_17/jre
java.io.tmpdir = /tmp
If you are using Java 8 or newer you should definitely choose PKCS12
, the default since Java 9 (JEP 229).
The advantages compared to JKS
and JCEKS
are:
PKCS12
is a standard format, it can be read by other programs and libraries1JKS
and JCEKS
are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 31 There is JDK-8202837, which has been fixed in Java 11
2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171
3 For further reading:
Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...
CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;
CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid),
INDEX(tmpid))
SELECT * FROM tmpLivecheck;
... solved my problem.
Greetings...
You can just read the data into a list and insert the new record where you want.
names = []
with open('names.txt', 'r+') as fd:
for line in fd:
names.append(line.split(' ')[-1].strip())
names.insert(2, "Charlie") # element 2 will be 3. in your list
fd.seek(0)
fd.truncate()
for i in xrange(len(names)):
fd.write("%d. %s\n" %(i + 1, names[i]))
Because the act of acquiring the position and getting the element from the given position naturally requires some locking (you can't have the list have structural changes between those two operations).
The very idea of a concurrent collection is that each operation on its own is atomic and can be done without explicit locking/synchronization.
Therefore getting the element at position n
from a given List
as an atomic operation doesn't make too much sense in a situation where concurrent access is anticipated.
I think you want $data[$category] = $question;
Or in case you want an array that maps categories to array of questions:
$data = array();
foreach($file_data as $value) {
list($category, $question) = explode('|', $value, 2);
if(!isset($data[$category])) {
$data[$category] = array();
}
$data[$category][] = $question;
}
print_r($data);
The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io
package name hints, the mentioned class is part of the http://commons.apache.org/io
project.
And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar
in the /WEB-INF/lib
as well.
I ended up doing the following and it works:
return DatabaseContext.Applications
.Include("Children.ChildRelationshipType");
Note that the downside of garbage-collecting your repository is that, well, the garbage gets collected. As we all know as computer users, files we consider garbage right now might turn out to be very valuable three days in the future. The fact that git keeps most of its debris around has saved my bacon several times – by browsing all the dangling commits, I have recovered much work that I had accidentally canned.
So don’t be too much of a neat freak in your private clones. There’s little need for it.
OTOH, the value of data recoverability is questionable for repos used mainly as remotes, eg. the place all the devs push to and/or pulled from. There, it might be sensible to kick off a GC run and a repacking frequently.
Below section add in to your web.config
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json"
publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
jdk-7u80-macosx-x64.dmg fix this problem.
Cross Join: http://www.dba-oracle.com/t_garmany_9_sql_cross_join.htm
TLDR; Generates a all possible combinations between 2 tables (Carthesian product)
(Full) Outer Join: http://www.w3schools.com/Sql/sql_join_full.asp
TLDR; Returns every row in both tables and also results that have the same values (matches in CONDITION)
You can use lambda in Java 8
public static void main(String[] args) {
tentimes(inputPrm - > System.out.println(inputPrm));
//tentimes(System.out::println); // You can also replace lambda with static method reference
}
public static void tentimes(Consumer myFunction) {
for (int i = 0; i < 10; i++)
myFunction.accept("hello");
}
For further info about Java Lambdas and FunctionalInterfaces
I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS
div {
opacity:0;
transition:opacity 1s linear;*
}
div.SomeClass {
opacity:1;
}
I don't think you'll get a better way than your function.
It is clean, easy to follow and understand, and returns the result of the condition (no return (...) ? true : false
mess).
Another solution would be to use Empty
.
Returns an empty IEnumerable that has the specified type argument.
IEnumerable<object> a = Enumerable.Empty<object>();
There is a thread on SO about it: Is it better to use Enumerable.Empty() as opposed to new List to initialize an IEnumerable?
If you use an empty array or empty list, those are objects and they are stored in memory. The Garbage Collector has to take care of them. If you are dealing with a high throughput application, it could be a noticeable impact.
Enumerable.Empty
does not create an object per call thus putting less load on the GC.
Go to the Config button (up right) and select the Autostart for Apache.
Another option that should require less "work" for the browser than html()
or children()
:
function isEmpty( el ){
return !el.has('*').length;
}
You can either use the prepareStatement
method taking an additional int
parameter
PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)
For some JDBC drivers (for example, Oracle) you have to explicitly list the column names or indices of the generated keys:
PreparedStatement ps = con.prepareStatement(sql, new String[]{"USER_ID"})
There are a lot of things to consider when validating a phone number if you really think about it. (especially international) so using a package is better than the accepted answer by far, and if you want something simple like a regex I would suggest using something better than what @SlateEntropy suggested. (something like A comprehensive regex for phone number validation)
I had a directory of files that I wanted to check. I created an Excel macro to determine ANSI vs. UTF-8. This worked for me.
Sub GetTextFileEncoding()
Dim sFile As String
Dim sPath As String
Dim sTextLine As String
Dim iRow As Integer
'Set Defaults and Initial Values
iRow = 1
sPath = "C:textfiles\"
sFile = Dir(sPath & "*.txt")
Do While Len(sFile) > 0
'Get FileType
'Debug.Print sFile & " - " & FileEncodeType(sPath & sFile)
'Show on Excel Worksheet
Cells(iRow, 1).Value = sFile
Cells(iRow, 2).Value = FileEncodeType(sPath & sFile)
'Get next file
sFile = Dir
'Increment Row
iRow = iRow + 1
Loop
End Sub
Function FileEncodeType(sFile As String) As String
Dim bEF As Boolean
Dim bBB As Boolean
Dim bBF As Boolean
bEF = False
bBB = False
bBF = False
Open sFile For Input As #1
If Not EOF(1) Then
'Read first line
Line Input #1, textline
'Debug.Print textline
For i = 1 To 3
'Debug.Print Asc(Mid(textline, i, 1)) & " - " & Mid(textline, i, 1)
Select Case i
Case 1
If Asc(Mid(textline, i, 1)) = 239 Then
bEF = True
End If
Case 2
If Asc(Mid(textline, i, 1)) = 187 Then
bBB = True
End If
Case 3
If Asc(Mid(textline, i, 1)) = 191 Then
bBF = True
End If
Case 4
End Select
Next
End If
Close #1
If bEF And bBB And bBF Then
FileEncodeType = "UTF-8"
Else
FileEncodeType = "ANSI"
End If
End Function
I think you can load it in a Word document object by using .NET office programmability support and Visual Studio tools for office.
And then use the document instance to re-save as an HTML document.
I am not sure how but I believe it is possible entirely in .NET without any 3rd party library.
I prefer the following to store any number of variables without having to create a separate class.
final public static Map<String, Map<String, Float>> myMap = new HashMap<String, Map<String, Float>>();
Use asp:image
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="images/image1.jpg"/>
and codebehind to change image url
Image1.ImageUrl = "/MyProject;component/Images/down.png";
To add to Tristan's answer, the button can also receive (id)event
in addition to (id)sender
:
- (IBAction) buttonTouchUpInside:(id)sender forEvent:(id)event { .... }
This can be useful if, for example, the button is in a cell in a UITableView
and you want to find the indexPath
of the button that was touched (although I suppose this can also be found via the sender
element).
git diff HEAD file
will show you changes you added to your worktree from the last commit. All the changes (staged or not staged) will be shown.
you can accomplish your task simply by implementing as below:
private Menu menu;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.drive_menu, menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
this.menu = menu;
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_toggle_grid) {
handleMenuOption(id);
return true;
} else if(id == R.id.action_toggle_list){
handleMenuOption(id);
return true;
}
return super.onOptionsItemSelected(item);
}
private void handleMenuOption(int id) {
MenuItem item = menu.findItem(id);
if (id == R.id.action_toggle_grid){
item.setVisible(false);
menu.findItem(R.id.action_toggle_list).setVisible(true);
}else if (id == R.id.action_toggle_list){
item.setVisible(false);
menu.findItem(R.id.action_toggle_grid).setVisible(true);
}
}
In recent Git (I'm using v2.15.1), the following will merge upstream submodule changes into the submodules recursively:
git submodule update --recursive --remote --merge
You may add --init
to initialize any uninitialized submodules and use --rebase
if you want to rebase instead of merge.
You need to commit the changes afterwards:
git add . && git commit -m 'Update submodules to latest revisions'
You can achieve this by setting content mode of image view to UIViewContentModeScaleAspectFill.
Then use following method method to get the resized uiimage object.
- (UIImage*)setProfileImage:(UIImage *)imageToResize onImageView:(UIImageView *)imageView
{
CGFloat width = imageToResize.size.width;
CGFloat height = imageToResize.size.height;
float scaleFactor;
if(width > height)
{
scaleFactor = imageView.frame.size.height / height;
}
else
{
scaleFactor = imageView.frame.size.width / width;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), NO, 0.0);
[imageToResize drawInRect:CGRectMake(0, 0, width * scaleFactor, height * scaleFactor)];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
Edited Here (Swift Version)
func setProfileImage(imageToResize: UIImage, onImageView: UIImageView) -> UIImage
{
let width = imageToResize.size.width
let height = imageToResize.size.height
var scaleFactor: CGFloat
if(width > height)
{
scaleFactor = onImageView.frame.size.height / height;
}
else
{
scaleFactor = onImageView.frame.size.width / width;
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(width * scaleFactor, height * scaleFactor), false, 0.0)
imageToResize.drawInRect(CGRectMake(0, 0, width * scaleFactor, height * scaleFactor))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return resizedImage;
}
Try this:
<div style="background:transparent !important" class="jumbotron">
<h1>Welcome!</h1>
<p>We're an awesome company that creates virtual things for portable devices.</p>
<p><a class="btn btn-primary btn-lg" role="button">Learn more</a></p>
</div>
Inline CSS gets preference over classes defined in a .css
file and the classes declared inside <style>
The thread you linked to does answer the question for you. You need to target the a
elements themselves. E.g.
.nav.navbar-nav.navbar-right a {
color: blue;
}
If that doesn't work, it just needs to be more specific. E.g.
.nav.navbar-nav.navbar-right li a {
color: blue;
}
If you absolutely must use HTML to give your text color, you have to use the (deprecated) <font>
-tag:
<h2><font color="#006699">Process Report</font></h2>
But otherwise, I strongly recommend you to do as rekire said: use CSS.
.catch(error => { throw error})
is a no-op. It results in unhandled rejection in route handler.
As explained in this answer, Express doesn't support promises, all rejections should be handled manually:
router.get("/emailfetch", authCheck, async (req, res, next) => {
try {
//listing messages in users mailbox
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
emailFetch = emailFetch.data
res.send(emailFetch)
} catch (err) {
next(err);
}
})
public event EventHandler ImageFullPath1Changed;
public string ImageFullPath1
{
get
{
// insert getter logic
}
set
{
// insert setter logic
// EDIT -- this example is not thread safe -- do not use in production code
if (ImageFullPath1Changed != null && value != _backingField)
ImageFullPath1Changed(this, new EventArgs(/*whatever*/);
}
}
That said, I completely agree with Ryan. This scenario is precisely why INotifyPropertyChanged exists.
Also you can add #include<vector>
in the header. When two of the above solutions don't work.
The pattern that matches substrings in parentheses having no other (
and )
characters in between (like (xyz 123)
in Text (abc(xyz 123)
) is
\([^()]*\)
Details:
\(
- an opening round bracket (note that in POSIX BRE, (
should be used, see sed
example below)[^()]*
- zero or more (due to the *
Kleene star quantifier) characters other than those defined in the negated character class/POSIX bracket expression, that is, any chars other than (
and )
\)
- a closing round bracket (no escaping in POSIX BRE allowed)Removing code snippets:
string.replace(/\([^()]*\)/g, '')
preg_replace('~\([^()]*\)~', '', $string)
$s =~ s/\([^()]*\)//g
re.sub(r'\([^()]*\)', '', s)
Regex.Replace(str, @"\([^()]*\)", string.Empty)
Regex.Replace(str, "\([^()]*\)", "")
s.replaceAll("\\([^()]*\\)", "")
s.gsub(/\([^()]*\)/, '')
gsub("\\([^()]*\\)", "", x)
string.gsub(s, "%([^()]*%)", "")
sed 's/([^()]*)//g'
regsub -all {\([^()]*\)} $s "" result
std::regex
: std::regex_replace(s, std::regex(R"(\([^()]*\))"), "")
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([^()]*\\)" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
s.replacingOccurrences(of: "\\([^()]*\\)", with: "", options: [.regularExpression])
Swift 3.1
import UIKit
extension UILabel {
var fontSize: CGFloat {
get {
return self.font.pointSize
}
set {
self.font = UIFont(name: self.font.fontName, size: newValue)!
self.sizeToFit()
}
}
}
For those who came here looking for the answer and didnt type 3306 wrong...If like myself, you have wasted hours with no luck searching for this answer, then possibly this may help.
If you are seeing this: (HY000/2002): No connection could be made because the target machine actively refused it
Then my understanding is that it cant connect for one of the following below. Now which..
1) is your wamp, mamp, etc icon GREEN? Either way, right-click the icon --> click tools --> test both the port used for Apache (typically 80) and for Mariadb (3307?). Should say 'It is correct' for both.
2) Error comes from a .php file. So, check your dbconnect.php.
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_pw";
$dbname = "your_dbname";
$port = "3307";
?>
Is your setup correct? Does your user exist? Do they have rights? Does port match the tested port in 1)? Doesn't have to be 3307 and user can be root. You can also left click the green icon --> click MariaDB and view used port as shown in the image below. All good? Positive? ok!
3) Error comes when you login to phpmyadmin. So, check your my.ini.
Open my.ini by left clicking the green icon --> click MariaDB -->
; The following options will be passed to all MariaDB clients
[client]
;password = your_password
port = 3307
socket = /tmp/mariadb.sock
; Here follows entries for some specific programs
; The MariaDB server
[wampmariadb64]
;skip-grant-tables
port = 3307
socket = /tmp/mariadb.sock
Make sure the ports match the port MariaDB is being testing on. Then finally..
[mysqld]
port = 3307
At the bottom of my.ini, make sure this port matches as well.
4) 1-3 done? restart your WAMP and cross your fingers!
The question is already answered but I wanted to point out another solution which is fast and works if length is not meant to be changed at run-time. Use macro #define before main() to define length and in main() your initialization will work:
#define length 10
int main()
{
int boardAux[length][length] = {{0}};
}
Macros are run before the actual compilation and length will be a compile-time constant (as referred by David Rodríguez in his answer). It will actually substitute length with 10 before compilation.
The text at the navigation bar is normally colored by using one of the two following css classes in the bootstrap.css
file.
Firstly, in case of using a default navigation bar (the gray one), the .navbar-default
class will be used and the text is colored as dark gray.
.navbar-default .navbar-text {
color: #777;
}
The other is in case of using an inverse navigation bar (the black one), the text is colored as gray60.
.navbar-inverse .navbar-text {
color: #999;
}
So, you can change its color as you wish. However, I would recommend you to use a separate css file to change it.
NOTE: you could also use the customizer provided by Twitter Bootstrap
, in the Navbar
section.
In my own case, i was using serialize()
on the form, Hence the files were not being sent to php. If you are using jquery, use FormData()
. For example
<form id='form'>
<input type='file' name='file' />
<input type='submit' />
</form>
Using jquery,
$('#form').submit(function (e) {
e.preventDefault();
var formData = new FormData(this); // grab all form contents including files
//you can then use formData and pass to ajax
});
You should edit "settings.json". In that add, "editor.lineNumbers":"on",
. You can check comments for various options you have.
In Visual Studio Code - 2017, you can also directly go to a given line number. There are following three ways to do that.
in "from queue import Queue
" there is no module called queue
, instead multiprocessing
should be used. Therefore, it should look like "from multiprocessing import Queue
"
yourbox {
position: absolute;
left: 100%;
top: 0;
}
left:100%; is the important issue here!
In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :
sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...
[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]
I had a similar problem . For this you can use a Hashmap which takes "string" and "object" as shown in code below:
/** stores the image database icons */
public static int[] imageIconDatabase = { R.drawable.ball,
R.drawable.catmouse, R.drawable.cube, R.drawable.fresh,
R.drawable.guitar, R.drawable.orange, R.drawable.teapot,
R.drawable.india, R.drawable.thailand, R.drawable.netherlands,
R.drawable.srilanka, R.drawable.pakistan,
};
private void initializeImageList() {
// TODO Auto-generated method stub
for (int i = 0; i < imageIconDatabase.length; i++) {
map = new HashMap<String, Object>();
map.put("Name", imageNameDatabase[i]);
map.put("Icon", imageIconDatabase[i]);
}
}
Depending on your automake version, you can also use this:
make AM_DEFAULT_VERBOSITY=1
Reference: AM_DEFAULT_VERBOSITY
Note: I added this answer since V=1
did not work for me.
To pass variables from node.js to html by using the res.render() method.
Example:
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render('index.html',{email:data.email,password:data.password});
});
This happened to me because I was using:
app.datasource.url=jdbc:mysql://localhost/test
When I replaced url by jdbc-url
then it worked:
app.datasource.jdbc-url=jdbc:mysql://localhost/test
I would suggest you to either use <table>
or CSS.
CSS is preferred for being more flexible. An example would be:
<!-- of course, you should move the inline CSS style to your stylesheet -->
<!-- main container, width = 70% of page, centered -->
<div id="contentBox" style="margin:0px auto; width:70%">
<!-- columns divs, float left, no margin so there is no space between column, width=1/3 -->
<div id="column1" style="float:left; margin:0; width:33%;">
CONTENT
</div>
<div id="column2" style="float:left; margin:0;width:33%;">
CONTENT
</div>
<div id="column3" style="float:left; margin:0;width:33%">
CONTENT
</div>
</div>
jsFiddle: http://jsfiddle.net/ndhqM/
Using float:left would make 3 columns stick to each other, coming in from left inside the centered div "content box".
Basically this is what you need to do:
in the first activity:
Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);
and in the second activtiy:
Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);
one of the get-functions will give return you the value, depending on the datatype you are passing through.
I tried the solution of Oskar (and many others) but for me it finaly only worked with:
jQuery(function($){
// Your jQuery code here, using the $
});
See: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
We can use infowindow.close(map); to close all info windows if you already initialize the info window using infowindow = new google.maps.InfoWindow();
Use zip(*list)
:
>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]
The zip()
function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l
you apply all tuples in l
as separate arguments to the zip()
function, so zip()
pairs up 1
with 3
with 8
first, then 2
with 4
and 9
. Those happen to correspond nicely with the columns, or the transposition of l
.
zip()
produces tuples; if you must have mutable list objects, just map()
the tuples to lists or use a list comprehension to produce a list of lists:
map(list, zip(*l)) # keep it a generator
[list(t) for t in zip(*l)] # consume the zip generator into a list of lists
For your purpose, you can just use
position: absolute;
top: 0%;
and it still be resizable, scrollable and responsive.
You can use org.apache.commons.lang.time.DateUtils
to make it cleaner:
(firstDate.getTime() - secondDate.getTime()) / DateUtils.MILLIS_PER_SECOND
I had the same problem, but I understand the VMware service is the problem. VMware host service and Apache service conflict together.
To Solve it » Run your task manager » in services tab find VMwareHostd » then right click and stop it » every thing have been solved.
If the current directory is empty, you can do that with:
git clone git@github:me/name.git .
(Note the .
at the end to specify the current directory.) Of course, this also creates the .git
directory in your current folder, not just the source code from your project.
This optional [directory]
parameter is documented in the git clone
manual page, which points out that cloning into an existing directory is only allowed if that directory is empty.
Try This , it will call validation for all control in form :
validateAllFormControl(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormControl(control);
}
});
}
You can wrap the label around the input:
**<label for="a"><input type="checkbox" id="a">a</label>**
This worked for me.