As a more general pattern to follow, I tend to use an @After
block in the test:
@After
public void after() {
verifyNoMoreInteractions(<your mock1>, <your mock2>...);
}
Then the test is free to verify only what should be called.
Also, I found that I often forgot to check for "no interactions", only to later discover that things were being called that shouldn't have been.
So I find this pattern useful for catching all unexpected calls that haven't specifically been verified.
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
JavaScript with a few modifications:
function deleteRow(btn) {
var row = btn.parentNode.parentNode;
row.parentNode.removeChild(row);
}
And the HTML with a little difference:
<table id="dsTable">
<tbody>
<tr>
<td>Relationship Type</td>
<td>Date of Birth</td>
<td>Gender</td>
</tr>
<tr>
<td>Spouse</td>
<td>1980-22-03</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
<tr>
<td>Child</td>
<td>2008-23-06</td>
<td>female</td>
<td><input type="button" value="Add" onclick="add()"/></td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"/></td>
</tr>
</tbody>
</table>???????????????????????????????????
If this is what you want ...simply add button inside the Fragment.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.LocationChooser">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|top"
android:text="Demo Button"
android:padding="10dp"
android:layout_marginTop="20dp"
android:paddingRight="10dp"/>
</fragment>
TLDR; Pandas groupby.agg
has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use
df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))
Mean Sum
dummy
1 0.036901 0.369012
OR
df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')
Mean Sum
dummy
1 0.036901 0.369012
Pandas has changed the behavior of GroupBy.agg
in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.
From the documentation,
To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in
GroupBy.agg()
, known as “named aggregation”, where
- The keywords are the output column names
- The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.
You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>)
.
import pandas as pd
pd.__version__
# '0.25.0.dev0+840.g989f912ee'
# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
'height': [9.1, 6.0, 9.5, 34.0],
'weight': [7.9, 7.5, 9.9, 198.0]
})
df.groupby('kind').agg(
max_height=('height', 'max'), min_weight=('weight', 'min'),)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
Alternatively, you can use pd.NamedAgg
(essentially a namedtuple) which makes things more explicit.
df.groupby('kind').agg(
max_height=pd.NamedAgg(column='height', aggfunc='max'),
min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
It is even simpler for Series, just pass the aggfunc to a keyword argument.
df.groupby('kind')['height'].agg(max_height='max', min_height='min')
max_height min_height
kind
cat 9.5 9.1
dog 34.0 6.0
Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:
df.groupby('kind')['height'].agg(**{'max height': 'max', ...})
In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning
:
df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed
# in a future version
Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.
df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})
returns
op1 op2
dummy
1 0.328953 0.032895
Or,
df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])
op1 op2
dummy
1 0.328953 0.032895
Also it may cause some warnigs in logs like a Cglib2AopProxy Unable to proxy method. And many other reasons for this are described here Why always have single implementaion interfaces in service and dao layers?
Here is what needs to go in D1: =VLOOKUP(C1, $A$1:$B$4, 2, FALSE)
You should then be able to copy this down to the rest of column D.
Do not apply an explicit width or height to the image tag. Instead, give it:
max-width:100%;
max-height:100%;
Also, height: auto;
if you want to specify a width only.
Example: http://jsfiddle.net/xwrvxser/1/
img {_x000D_
max-width: 100%;_x000D_
max-height: 100%;_x000D_
}_x000D_
_x000D_
.portrait {_x000D_
height: 80px;_x000D_
width: 30px;_x000D_
}_x000D_
_x000D_
.landscape {_x000D_
height: 30px;_x000D_
width: 80px;_x000D_
}_x000D_
_x000D_
.square {_x000D_
height: 75px;_x000D_
width: 75px;_x000D_
}
_x000D_
Portrait Div_x000D_
<div class="portrait">_x000D_
<img src="http://i.stack.imgur.com/xkF9Q.jpg">_x000D_
</div>_x000D_
_x000D_
Landscape Div_x000D_
<div class="landscape">_x000D_
<img src="http://i.stack.imgur.com/xkF9Q.jpg">_x000D_
</div>_x000D_
_x000D_
Square Div_x000D_
<div class="square">_x000D_
<img src="http://i.stack.imgur.com/xkF9Q.jpg">_x000D_
</div>
_x000D_
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
I had similar problem. I r?n npm cache clear
, closed android SDK manager(which was open before) and re-ran npm install -g cordova
and that was enough to solve the problem.
Yeah, as others have suggested, this error seems to mean that ssh-agent is installed but its service (on windows) hasn't been started.
You can check this by running in Windows PowerShell:
> Get-Service ssh-agent
And then check the output of status is not running.
Status Name DisplayName
------ ---- -----------
Stopped ssh-agent OpenSSH Authentication Agent
Then check that the service has been disabled by running
> Get-Service ssh-agent | Select StartType
StartType
---------
Disabled
I suggest setting the service to start manually. This means that as soon as you run ssh-agent, it'll start the service. You can do this through the Services GUI or you can run the command in admin mode:
> Get-Service -Name ssh-agent | Set-Service -StartupType Manual
Alternatively, you can set it through the GUI if you prefer.
I am not very sure whether it will make any difference in performance of my API.
Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async
" considerations in my article on async
ASP.NET.
I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.
As far as the code goes, this is not asynchronous:
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
return Task.FromResult(response);
}
You'd need a truly asynchronous implementation to get the scalability benefits of async
:
public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
Or (if your logic in this method really is just a pass-through):
public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}
Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync
). Then let the async
trickle up, making your controller actions asynchronous as the last step.
And under no circumstances should you use Task.Run
in this scenario.
Keep in mind, the following is not intended to be a substitute for a proper security solution.
After playing around with this for four days, I've put together a solution using only the open source System.Data.SQLite package from NuGet. I don't know how much protection this provides. I'm only using it for my own course of study. This will create the DB, encrypt it, create a table, and add data.
using System.Data.SQLite;
namespace EncryptDB
{
class Program
{
static void Main(string[] args)
{
string connectionString = @"C:\Programming\sqlite3\db.db";
string passwordString = "password";
byte[] passwordBytes = GetBytes(passwordString);
SQLiteConnection.CreateFile(connectionString);
SQLiteConnection conn = new SQLiteConnection("Data Source=" + connectionString + ";Version=3;");
conn.SetPassword(passwordBytes);
conn.Open();
SQLiteCommand sqlCmd = new SQLiteCommand("CREATE TABLE data(filename TEXT, filepath TEXT, filelength INTEGER, directory TEXT)", conn);
sqlCmd.ExecuteNonQuery();
sqlCmd = new SQLiteCommand("INSERT INTO data VALUES('name', 'path', 200, 'dir')", conn);
sqlCmd.ExecuteNonQuery();
conn.Close();
}
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
bytes = System.Text.Encoding.Default.GetBytes(str);
return bytes;
}
}
}
Optionally, you can remove conn.SetPassword(passwordBytes);
, and replace it with conn.ChangePassword("password");
which needs to be placed after conn.Open();
instead of before. Then you won't need the GetBytes method.
To decrypt, it's just a matter of putting the password in your connection string before the call to open.
string filename = @"C:\Programming\sqlite3\db.db";
string passwordString = "password";
SQLiteConnection conn = new SQLiteConnection("Data Source=" + filename + ";Version=3;Password=" + passwordString + ";");
conn.Open();
Using zsh
you can simply use:
if [[ $(false)? -eq 1 ]]; then echo "yes" ;fi
When using bash
& set -e
is on you can use:
false || exit_code=$?
if [[ ${exit_code} -ne 0 ]]; then echo ${exit_code}; fi
Use this code
using System.Threading;
// ...
Thread.Sleep(50);
For those who are not satisfied with the mentioned (excellent) posts, you can use your programming skills to make a variable (PHP or whichever) and have it store the multiple class names.
That's the best hack I could come up with.
<style>
.red { color: red; }
.bold { font-weight: bold; }
</style>
<? define('DANGERTEXT','red bold'); ?>
Then apply the global variable to the element you desire rather than the class names themselves
<span class="<?=DANGERTEXT?>"> Le Champion est Ici </span>
To resolve this, you should open up a terminal window and type this command:
sudo chown -R user ~/.composer
(with user
being your current user, in your case, kramer65
)
After you have ran this command, you should have permission to run your composer global require command.
You may also need to remove the .composer file from the current directory, to do this open up a terminal window and type this command:
sudo rm -rf .composer
Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.
tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
exit 0
Looks like something has changed for the better, because code below works perfectly for me, but I didn't find it in already provided answers.
Kotlin:
supportFragmentManager.fragments[supportFragmentManager.fragments.size - 1]
Java:
getSupportFragmentManager().getFragments()
.get(getSupportFragmentManager().getFragments().size() - 1)
Not sure it applies here also but in the case of protractor when using navigate().to(...)
the history is being kept but when using get()
it is lost.
One of my test was failing because I was using get()
2 times in a row and then doing a navigate().back()
. Because the history was lost, when going back it went to the about page and an error was thrown:
Error: Error while waiting for Protractor to sync with the page: {}
Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.
Function
function print_r(printthis, returnoutput) {
var output = '';
if($.isArray(printthis) || typeof(printthis) == 'object') {
for(var i in printthis) {
output += i + ' : ' + print_r(printthis[i], true) + '\n';
}
}else {
output += printthis;
}
if(returnoutput && returnoutput == true) {
return output;
}else {
alert(output);
}
}
Usage
var data = [1, 2, 3, 4];
print_r(data);
I use something like this (you should add code to deal with the various fails):
var response = RunTaskWithTimeout<ReturnType>(
(Func<ReturnType>)delegate { return SomeMethod(someInput); }, 30);
/// <summary>
/// Generic method to run a task on a background thread with a specific timeout, if the task fails,
/// notifies a user
/// </summary>
/// <typeparam name="T">Return type of function</typeparam>
/// <param name="TaskAction">Function delegate for task to perform</param>
/// <param name="TimeoutSeconds">Time to allow before task times out</param>
/// <returns></returns>
private T RunTaskWithTimeout<T>(Func<T> TaskAction, int TimeoutSeconds)
{
Task<T> backgroundTask;
try
{
backgroundTask = Task.Factory.StartNew(TaskAction);
backgroundTask.Wait(new TimeSpan(0, 0, TimeoutSeconds));
}
catch (AggregateException ex)
{
// task failed
var failMessage = ex.Flatten().InnerException.Message);
return default(T);
}
catch (Exception ex)
{
// task failed
var failMessage = ex.Message;
return default(T);
}
if (!backgroundTask.IsCompleted)
{
// task timed out
return default(T);
}
// task succeeded
return backgroundTask.Result;
}
In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.
Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.
There are two ways to do it..Say String==null or string.equals()..
public class IfElse {
public int ifElseTesting(String a){
//return null;
return (a== null)? 0: a.length();
}
}
public class ShortCutifElseTesting {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("enter the string please:");
String a=scanner.nextLine();
/*
if (a.equals(null)){
System.out.println("you are not correct");
}
else if(a.equals("bangladesh")){
System.out.println("you are right");
}
else
System.out.println("succesful tested");
*/
IfElse ie=new IfElse();
int result=ie.ifElseTesting(a);
System.out.println(result);
}
}
Check this example..Here is an another example of shortcut version of If Else..
I would try to avoid changing the xticklabels
if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.
Defining the range of your grid is probably the best and with imshow
it can be done by adding the extent
keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks
with perhaps some formatter. Altering the labels directly should be the last resort.
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio
9007199254740992 (that's 9,007,199,254,740,992) with no guarantees :)
Program
#include <math.h>
#include <stdio.h>
int main(void) {
double dbl = 0; /* I started with 9007199254000000, a little less than 2^53 */
while (dbl + 1 != dbl) dbl++;
printf("%.0f\n", dbl - 1);
printf("%.0f\n", dbl);
printf("%.0f\n", dbl + 1);
return 0;
}
Result
9007199254740991 9007199254740992 9007199254740992
Change the wrapping from "onload
" to "No wrap - in <body>
"
The function defined has a different scope.
Another short way
function filterByKey(v,keys){
const newObj ={};
keys.forEach(key=>{v[key]?newObj[key]=v[key]:''});
return newObj;
}
//given
let obj ={ foo: "bar", baz: 42,baz2:"blabla" , "spider":"man", monkey:true};
//when
let outObj =filterByKey(obj,["bar","baz2","monkey"]);
//then
console.log(outObj);
//{
// "baz2": "blabla",
// "monkey": true
//}
_x000D_
Hex to Decimal Conversion
Convert.ToInt32(number, 16);
Decimal to Hex Conversion
int.Parse(number, System.Globalization.NumberStyles.HexNumber)
If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.
If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.
While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:
makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer
(^ = allow batch command-line to wrap line)
This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).
The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.
Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:
certutil -user -addstore Root MyCA.cer
makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
-sky signature ^
-ic MyCA.cer -iv MyCA.pvk ^
-sv MySPC.pvk MySPC.cer
It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).
We'll also want to convert the certificate and key into a PFX file:
pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx
If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.
signtool sign /v /f MySPC.pfx ^
/t http://timestamp.url MyExecutable.exe
(See why timestamps may matter)
If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:
signtool sign /v /n "Me" /s SPC ^
/t http://timestamp.url MyExecutable.exe
Some possible timestamp URLs for signtool /t
are:
http://timestamp.verisign.com/scripts/timstamp.dll
http://timestamp.globalsign.com/scripts/timstamp.dll
http://timestamp.comodoca.com/authenticode
For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1
). Your mileage may vary.
MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).
It points to your top level output directory (which by default is target
):
EDIT: As has been pointed out, Codehaus is now sadly defunct. You can find details about these properties from Sonatype here:
If you are ever trying to reference output directories in Maven, you should never use a literal value like target/classes. Instead you should use property references to refer to these directories.
project.build.sourceDirectory project.build.scriptSourceDirectory project.build.testSourceDirectory project.build.outputDirectory project.build.testOutputDirectory project.build.directory
sourceDirectory
,scriptSourceDirectory
, andtestSourceDirectory
provide access to the source directories for the project.outputDirectory
andtestOutputDirectory
provide access to the directories where Maven is going to put bytecode or other build output.directory
refers to the directory which contains all of these output directories.
You can try the Class Based View called RedirectView
from django.views.generic.base import RedirectView
urlpatterns = patterns('',
url(r'^$', 'macmonster.views.home'),
#url(r'^macmon_home$', 'macmonster.views.home'),
url(r'^macmon_output/$', 'macmonster.views.output'),
url(r'^macmon_about/$', 'macmonster.views.about'),
url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)
Notice how as url
in the <url_to_home_view>
you need to actually specify the url.
permanent=False
will return HTTP 302, while permanent=True
will return HTTP 301.
Alternatively you can use django.shortcuts.redirect
Update for Django 2+ versions
With Django 2+, url()
is deprecated and replaced by re_path()
. Usage is exactly the same as url()
with regular expressions. For replacements without the need of regular expression, use path()
.
from django.urls import re_path
re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
This method should be helpful..!
public Activity getActivityByContext(Context context){
if(context == null){
return null;
}
else if((context instanceof ContextWrapper) && (context instanceof Activity)){
return (Activity) context;
}
else if(context instanceof ContextWrapper){
return getActivity(((ContextWrapper) context).getBaseContext());
}
return null;
}
I hope this helps.. Merry coding!
# s1 == source string
# char == find this character
# repl == replace with this character
def findreplace(s1, char, repl):
s1 = s1.replace(char, repl)
return s1
# find each 'i' in the string and replace with a 'u'
print findreplace('it is icy', 'i', 'u')
# output
''' ut us ucy '''
you should read the file, every time you want to add a new property to the json, and then add the the new properties
var fs = require('fs');
fs.readFile('data.json',function(err,content){
if(err) throw err;
var parseJson = JSON.parse(content);
for (i=0; i <11 ; i++){
parseJson.table.push({id:i, square:i*i})
}
fs.writeFile('data.json',JSON.stringify(parseJson),function(err){
if(err) throw err;
})
})
You can use the LocalCommand
command-line option if the PermitLocalCommand
option is enabled:
ssh username@hostname -o LocalCommand="tmux list-sessions"
For more details about the available options, see the ssh_config
man page.
I was facing the same problem when import projects into IntelliJ.
for in my case first, check SDK details and check you have configured JDK correctly or not.
Go to File-> Project Structure-> platform Settings-> SDKs
Check your JDK is correct or not.
Next, I Removed project from IntelliJ and delete all IntelliJ and IDE related files and folder from the project folder (.idea, .settings, .classpath, dependency-reduced-pom). Also, delete the target folder and re-import the project.
The above solution worked in my case.
function get_daydiff($end_date,$today)
{
if($today=='')
{
$today=date('Y-m-d');
}
$str = floor(strtotime($end_date)/(60*60*24)) - floor(strtotime($today)/(60*60*24));
return $str;
}
$d1 = "2018-12-31";
$d2 = "2018-06-06";
echo get_daydiff($d1, $d2);
# reorder by column name
data <- data[c("A", "B", "C")]
#reorder by column index
data <- data[c(1,3,2)]
If you want to use reflection and set columns order/ include only some columns/ Exclude some columns try this:
private static DataTable ConvertToDataTable<T>(IList<T> data, string[] fieldsToInclude = null,
string[] fieldsToExclude = null)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
{
if ((fieldsToInclude != null && !fieldsToInclude.Contains(prop.Name)) ||
(fieldsToExclude != null && fieldsToExclude.Contains(prop.Name)))
continue;
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
foreach (T item in data)
{
var atLeastOnePropertyExists = false;
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
if ((fieldsToInclude != null && !fieldsToInclude.Contains(prop.Name)) ||
(fieldsToExclude != null && fieldsToExclude.Contains(prop.Name)))
continue;
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
atLeastOnePropertyExists = true;
}
if(atLeastOnePropertyExists) table.Rows.Add(row);
}
if (fieldsToInclude != null)
SetColumnsOrder(table, fieldsToInclude);
return table;
}
private static void SetColumnsOrder(DataTable table, params String[] columnNames)
{
int columnIndex = 0;
foreach (var columnName in columnNames)
{
table.Columns[columnName].SetOrdinal(columnIndex);
columnIndex++;
}
}
The html
<select id="drop" name="company" class="company btn btn-outline dropdown-toggle" >
<option value="demo1">Group Medical</option>
<option value="demo">Motor Insurance</option>
</select>
Script.js
$("#drop").change(function () {
var category= $('select[name=company]').val() // Here we can get the value of selected item
alert(category);
});
As my recent experiments led me into depths of PowerShell and .NET calls, I must say that PowerShell can replace Cygwin and Unix shell.
I'm not sure about Perl, but since both PowerShell and Perl are Turing complete as programming languages, I give this as a yes to replacing Perl too.
One thing that PowerShell has above Cygwin and ordinary Bash under *nix, is its ability to perform sandboxed DLL calls, manipulating the operating system via direct API calls, WMI methods and even COM objects. How about launching Internet Explorer via code, then doing whatever you want with its displayed document, effectively emulating a back-end for a Web server?
How about gathering data from SQL servers and other data providers, parse them and export as CSV, mail messages, text and actually any kind of existing and non-existing file formats? (With proper skills of creating a valid file out of data received, of course, but CSV are readily available).
And there is an extra security available via signed cmdlets and scripts, group policies, and execution policies that help prevent malicious code from running on your system even if you run them as administrator.
About what commands are implemented - the answer by Richard lists them and PowerShell's capability of emulating their functionality already.
About whether PowerShell is strong to warrant switching over - this is more a matter of personal preference, although as more and more Windows services are providing PowerShell cmdlets to control them, not using PowerShell with these services present is considered a hindrance. (Hyper-V server is the primary such service, and it also provides the ability to do more with PowerShell cmdlets than with GUI!)
Probably this answer is five years late, but still, if someone performs administrative tasks or general scripting of various stuff on Windows, they should definitely try harnessing PowerShell for their purposes.
For the revised question of how to read in configuration parameters, I'd strongly recommend saving yourself some time and effort and use ConfigParser or (my preferred tool) ConfigObj.
They can do everything you need, they're easy to use, and someone else has already worried about how to get them to work properly!
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
ArrayList<Matrices> list = new ArrayList<Matrices>();
list.add( new Matrices(1,1,10) );
list.add( new Matrices(1,2,20) );
Just to clarify, be aware bracket placement is important!
These can be added to any HTML tags... span, div, table, p, tr, td etc.
AngularJS
ng-if="check1 && !check2" -- AND NOT
ng-if="check1 || check2" -- OR
ng-if="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
Angular2+
*ngIf="check1 && !check2" -- AND NOT
*ngIf="check1 || check2" -- OR
*ngIf="(check1 || check2) && check3" -- AND/OR - Make sure to use brackets
It's best practice not to do calculations directly within ngIfs, so assign the variables within your component, and do any logic there.
boolean check1 = Your conditional check here...
...
It should work the way you intended.
$array = array('value-0', 'value-1', 'value-2', 'value-3', 'value-4', 'value-5' /* … */);
$key = 4;
$value = $array[$key];
echo $value; // value-4
But maybe there is no element with the key 4
. If you want to get the fiveth item no matter what key it has, you can use array_slice
:
$value = array_slice($array, 4, 1);
Maybe try this:
ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
If i remember correctly, you need to use the "Shapes" property of your sheet.
Each Shape object has a TopLeftCell and BottomRightCell attributes that tell you the position of the image.
Here's a piece of code i used a while ago, roughly adapted to your needs. I don't remember the specifics about all those ChartObjects and whatnot, but here it is:
For Each oShape In ActiveSheet.Shapes
strImageName = ActiveSheet.Cells(oShape.TopLeftCell.Row, 1).Value
oShape.Select
'Picture format initialization
Selection.ShapeRange.PictureFormat.Contrast = 0.5: Selection.ShapeRange.PictureFormat.Brightness = 0.5: Selection.ShapeRange.PictureFormat.ColorType = msoPictureAutomatic: Selection.ShapeRange.PictureFormat.TransparentBackground = msoFalse: Selection.ShapeRange.Fill.Visible = msoFalse: Selection.ShapeRange.Line.Visible = msoFalse: Selection.ShapeRange.Rotation = 0#: Selection.ShapeRange.PictureFormat.CropLeft = 0#: Selection.ShapeRange.PictureFormat.CropRight = 0#: Selection.ShapeRange.PictureFormat.CropTop = 0#: Selection.ShapeRange.PictureFormat.CropBottom = 0#: Selection.ShapeRange.ScaleHeight 1#, msoTrue, msoScaleFromTopLeft: Selection.ShapeRange.ScaleWidth 1#, msoTrue, msoScaleFromTopLeft
'/Picture format initialization
Application.Selection.CopyPicture
Set oDia = ActiveSheet.ChartObjects.Add(0, 0, oShape.Width, oShape.Height)
Set oChartArea = oDia.Chart
oDia.Activate
With oChartArea
.ChartArea.Select
.Paste
.Export ("H:\Webshop_Zpider\Strukturbildene\" & strImageName & ".jpg")
End With
oDia.Delete 'oChartArea.Delete
Next
The JSON spec says this:
An object is an unordered set of name/value pairs.
The important part here is "unordered": it implies uniqueness of keys, because the only thing you can use to refer to a specific pair is its key.
In addition, most JSON libs will deserialize JSON objects to hash maps/dictionaries, where keys are guaranteed unique. What happens when you deserialize a JSON object with duplicate keys depends on the library: in most cases, you'll either get an error, or only the last value for each duplicate key will be taken into account.
For example, in Python, json.loads('{"a": 1, "a": 2}')
returns {"a": 2}
.
I know my code is little length and little time complexity but it's understandable so I tried this way.
I'm trying to develop prototype based function here and code also change.
Here,Distinct is my own prototype function.
<script>_x000D_
var array = [{_x000D_
"name": "Joe",_x000D_
"age": 17_x000D_
},_x000D_
{_x000D_
"name": "Bob",_x000D_
"age": 17_x000D_
},_x000D_
{_x000D_
"name": "Carl",_x000D_
"age": 35_x000D_
}_x000D_
]_x000D_
_x000D_
Array.prototype.Distinct = () => {_x000D_
var output = [];_x000D_
for (let i = 0; i < array.length; i++) {_x000D_
let flag = true;_x000D_
for (let j = 0; j < output.length; j++) {_x000D_
if (array[i].age == output[j]) {_x000D_
flag = false;_x000D_
break;_x000D_
}_x000D_
}_x000D_
if (flag)_x000D_
output.push(array[i].age);_x000D_
}_x000D_
return output;_x000D_
}_x000D_
//Distinct is my own function_x000D_
console.log(array.Distinct());_x000D_
</script>
_x000D_
For the lazy and the learning, to put it into your theme, Rfvgyhn's full code
<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>
It is just an overload. The add
method is from the ArrayList
class. Look that Staff
inherits from it.
You simply can't use View as a Header of ListView.
Because the view which is being passed in has to be inflated.
Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.
EDIT:
Look at this tutorial Android ListView and ListActivity - Tutorial .
EDIT 2: This link is broken Android ListActivity with a header or footer
Just like you do for getting something from the CNode
you also need to do for the ANode
XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
XmlNode anode = xn.SelectSingleNode("ANode");
if (anode!= null)
{
string id = anode["ID"].InnerText;
string date = anode["Date"].InnerText;
XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
foreach (XmlNode node in CNodes)
{
XmlNode example = node.SelectSingleNode("Example");
if (example != null)
{
string na = example["Name"].InnerText;
string no = example["NO"].InnerText;
}
}
}
}
Go and Check if a user is created or not if no please create a user by opening a file in /apache-tomcat-9.0.20/tomcat-users.xml add a line into it
<user username="tomcat" password="tomcat" roles="admin-gui,manager-gui,manager-script" />
Goto /apache-tomcat-9.0.20/webapps/manager/META-INF/ open context.xml comment everything in context tag example:
<Context antiResourceLocking="false" privileged="true" >
<!--Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /-->
</Context>
John Montgomery's, answer is great, but at least on Windows, it is missing the line
vc.release()
before
cv2.destroyWindow("preview")
Without it, the camera resource is locked, and can not be captured again before the python console is killed.
JSONP is an old trick invented to bypass the security restriction that forbids us to get JSON data that is in a different website (a different origin1) than the one we are navigating in.
The trick works by using a <script>
tag that asks for the JSON from that place, e.g.: { "user":"Smith" }
, but wrapped in a function, the actual JSONP ("JSON with Padding"):
peopleDataJSONP({"user":"Smith"})
Receiving it in this form enables us to use the data within our peopleDataJSONP
function. JSONP is a bad practice and not needed anymore, don't use it (read below).
Say we want to use on ourweb.com
some JSON data (or any raw data really) hosted at anotherweb.com
. If we were to use GET request (think XMLHttpRequest
, or fetch
call, $.ajax
, etc.), our browser would tell us it's not allowed with this ugly error:
How to get the data we want? Well, <script>
tags are not subjected to this whole server (origin1) restriction! That's why we can load a library like jQuery or Google Maps from any server, such as a CDN, without any errors.
Here's the important point: if you think about it, those libraries are actual, runnable JS code (usually a massive function with all the logic inside). But raw data? JSON data is not code. There's nothing to run; it's just plain text.
Therefore, there's no way to handle or manipulate our precious data. The browser will download the data pointed at by our <script>
tag and when processing it'll rightfully complain:
wtf is this
{"user":"Smith"}
crap we loaded? It's not code. I can't compute, syntax error!
The old/hacky way to utilize that data? If we could make plain text somehow runnable, we could grab it on runtime. So we need anotherweb.com
to send it with some logic, so when it's loaded, your code in the browser will be able to use said data. We need two things: 1) to get the data in a way that it can be run, and 2) write some code in the client so that when the data runs, this code is called and we get to use the data.
For 1) we ask the foreign server to send us the JSON data inside a JS function. The data itself is set up as that function's input. It looks like this:
peopleDataJSONP({"user":"Smith"})
which makes it JS code our browser will parse and run without complaining! Exactly like it does with the jQuery library. To receive the data like that, the client "asks" the JSONP-friendly server for it, usually done like this:
<script src="https://anotherweb.com/api/data-from-people.json?myCallback=peopleDataJSONP"></script>
As per 2), since our browser will receive the JSONP with that function name, we need a function with the same name in our code, like this:
function peopleDataJSONP(data){
alert(data.user); // "Smith"
}
The browser will download the JSONP and run it, which calls our function, where the argument data
will be the JSON data from anotherweb.com
. We can now do with our data whatever we want to.
JSONP is a cross-site hack with a few downsides:
The takeaway is that there's no need to use it nowadays.
You should read about CORS here, but the gist of it is:
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.
https://web.com
is a different origin than http://web.com
(different protocol) and https://web.com:8081
(different port) and obviously https://thatotherweb.net
(different host)Just for completeness, this also works
from IPython.core.pylabtools import figsize
figsize(14, 7)
It is a wrapper aroung the rcParams
solution
If you are in a shared hosting plan that doesn't have PHP installed as a module you will get a 500 server error when adding those flags to the .htaccess file.
But you can add the line
ini_set('display_errors','off');
on top of your .php file and it should work without any errors.
A "reference" in docker is a pointer to an image. It may be an image name, an image ID, include a registry server in the name, use a sha256 tag to pin the image, and anything else that can be used to point to the image you want to run.
The invalid reference format
error message means docker cannot convert the string you've provided to an image. This may be an invalid name, or it may be from a parsing error earlier in the docker run
command line if that's how you run the image. With a compose file, if you expand a variable in the image name, that variable may not be expanding correctly.
With the docker run
command line, this is often the result in not quoting parameters with spaces, and mistaking the order of the command line. The command line is ordered as:
docker ${args_to_docker} run ${args_to_run} image_ref ${cmd_to_exec}
The most common error in passing args to the run is a volume mapping expanding a path name that includes a space in it, and not quoting the path or escaping the space. E.g.
docker run -v $(pwd):/data image_ref
And the fix is as easy as:
docker run -v "$(pwd):/data" image_ref
I had the exact same problem. The way I solved it on Mac is this:
You could use something like this to give your button a value:
<?php
if (isset($_POST['submit'])) {
$aSubmitVal = array_keys($_POST['submit'])[0];
echo 'The button value is: ' . $aSubmitVal;
}
?>
<form action="/" method="post">
<input id="someId" type="submit" name="submit[SomeValue]" value="Button name">
</form>
This will give you the string "SomeValue" as a result
Use anchors instead:
aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)
These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^
anchor because it's implicit in the .match()
method).
Then, check if the regex did in fact match before trying to access its results:
if aa:
ip = aa.group()
Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:
ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)
Here, the \b
word boundary anchors make sure that the digits don't exceed 3 for each segment.
padding: EdgeInsets.only(
left: 4.0,
right: ResponsiveWidget.isSmallScreen(context) ? 4: 74, //Check for screen type
top: 10,
bottom: 40),
This is fine by Google's recommendation but may be not perfect.
$("#id").select2("val", null); //this will not work..you can try
You should actually do this...intialise and then set the value..well this is also the way it worked for me.
$("#id").select2().select2("val", null);
$("#id").select2().select2("val", 'oneofthevaluehere');
Yii::app()->request->url
Yii::$app->request->url
Floating point numbers only have so many significant digits, but they can go much higher. If your app will ever handle large numbers, you will notice the epsilon value should be different.
0.001+0.001 = 0.002 BUT 12,345,678,900,000,000,000,000+1=12,345,678,900,000,000,000,000 if you are using floating point and double. It's not a good representation of money, unless you are damn sure you'll never handle more than a million dollars in this system.
If you don't want to use an external library, or store an array of month names, or if the ECMAScript Internationalization API is not good enough because of browser compatibility you can always do it the old-fashioned way by extracting the info from the date output:
var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);
This would give you the abbreviated month name, e.g. Oct. I believe the date will come in all sorts of formats depending on the initialization and your locale so take a look at what toDateString()
returns and recalculate your substring()
values based on that.
you can try
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));
Document doc = db.parse(is);
refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm
The second parameter of axios.post
is data
(not config
). config
is the third parameter. Please see this for details: https://github.com/mzabriskie/axios#axiosposturl-data-config
Its very simple, 1)Just go on directory where the file us stored 2)then enter command i.e. type filename.file_extention e.g type MyFile.tx
I encountered this problem when my operating system was in French, and I was installing Wampserver in English.
I am pretty sure that Microsoft Redistributable packages were installed since I was already working with Visual Studio. I think the issue may have been because of changes in path names with different languages. However, when I installed wampserver in French, everything worked perfectly.
If you don't care about the compatibility with older IE versions (< 8), you could make a custom jQuery plugin and then call it on the overflowing element.
This solution has an advantage over the one Šime Vidas proposed, as it doesn't overwrite the scrolling behavior - it just blocks it when appropriate.
$.fn.isolatedScroll = function() {
this.bind('mousewheel DOMMouseScroll', function (e) {
var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.detail,
bottomOverflow = this.scrollTop + $(this).outerHeight() - this.scrollHeight >= 0,
topOverflow = this.scrollTop <= 0;
if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
e.preventDefault();
}
});
return this;
};
$('.scrollable').isolatedScroll();
You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0"
).
Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.
Here's how you can do it with Markdown:
![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)
You can use vscode with GitLens, it's a very powerful tool.
After installed GitLens, go to GitLens tab, select FILE HISTORY
and you can browse it.
Try the (unofficial) binaries in this site:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
You can get the newest numpy
x64 with or without Intel MKL libs for Python 2.7 or Python 3.
why do I have to pass seconds = uptime to timedelta
Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int
is superfluous as they could also accept floats.
and why does the string casting works so nicely that I get HH:MM:SS ?
It's not the typecasting that formats, is the internal __str__
method of the object. In fact you will achieve the same result if you write:
print datetime.timedelta(seconds=int(uptime))
You can also replace without a regular expression.
while(str.indexOf(' ')!=-1)str.replace(' ',' ');
I consider state to be for view only information and data that should persist beyond the view state is better stored as props. URL params are useful when you want to be able to link to a page or share the URL deep in to the app but otherwise clutter the address bar.
Take a look at Redux-Persist (if you're using redux) https://github.com/rt2zz/redux-persist
If you are using sagemath cloud version, you can simply go to the left corner,
select File --> Download as --> Pdf via LaTeX (.pdf)
Check the screenshot if you want.
Screenshot Convert ipynb to pdf
If it dosn't work for any reason, you can try another way.
select File --> Print Preview and then on the preview
right click --> Print and then select save as pdf.
Methods that use isNaN do not work if you're trying to use parseInt, for example:
parseInt("abc"); // NaN
parseInt(""); // NaN
parseInt("14px"); // 14
But in the second case isNaN produces false (i.e. the null string is a number)
n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
n=""; isNaN(n) ? 0: parseInt(n); // NaN
n="14px"; isNaN(n) ? 0 : parseInt(n); // 14
In summary, the null string is considered a valid number by isNaN but not by parseInt. Verified with Safari, Firefox and Chrome on OSX Mojave.
This worked for me
<img src="data:image;base64,@System.Convert.ToBase64String(Model.CategoryPicture.Content)" width="80" height="80"/>
You can't explicitly free memory. What you need to do is to make sure you don't keep references to objects. They will then be garbage collected, freeing the memory.
In your case, when you need large lists, you typically need to reorganize the code, typically using generators/iterators instead. That way you don't need to have the large lists in memory at all.
http://www.prasannatech.net/2009/07/introduction-python-generators.html
<a onclick="getCategoryIndex(${myIndex.index})" href="#">${categoryName}</a>
above line was giving me an error. So I wrote down in below way which is working fine for me.
<a onclick="getCategoryIndex('<c:out value="${myIndex.index}"/>')" href="#">${categoryName}</a>
Maybe someone else might get same error. Look at this guys!
This site Android Create AVD shows you how to install the latest version of the Android SDK and AVD version 4 in Eclipse with video and screenshots if you're still stuck?
As of Helios Service Release 2, there is no longer support for JAR files.You can add them, but Eclipse will not recognize them as libraries, therefore you can only "import" but can never use.
//Example to define how to do :
DataTable dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("Address");
dt.Columns.Add("City");
// The table structure is:
//ID FirstName LastName Address City
//Now we want to add a PhoneNo column after the LastName column. For this we use the
//SetOrdinal function, as iin:
dt.Columns.Add("PhoneNo").SetOrdinal(3);
//3 is the position number and positions start from 0.`enter code here`
//Now the table structure will be:
// ID FirstName LastName PhoneNo Address City
In order to not have the Cannot recover key
exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.
Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy
. Setting that to unlimited
with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty()
or via the java.security
file. The java.security
file could also be appended to by adding -Djava.security.properties=my_security.properties
to the command to start the program as detailed here.
Since JDK 8u161 unlimited cryptography is enabled by default.
Use the -printcert
command like this:
keytool -printcert -file certificate.pem
set ORACLE_SID=<YOUR_SID>
sqlplus "/as sysdba"
alter system disable restricted session;
or maybe
shutdown abort;
or maybe
lsnrctl stop
lsnrctl start
Android has a TextUtil class you can use http://developer.android.com/reference/android/text/TextUtils.html
String implode = TextUtils.join("\t", list);
When you create your table, put your td with class = "suma"
$(function(){
//funcion suma todo
var sum = 0;
$('.suma').each(function(x,y){
sum += parseInt($(this).text());
})
$('#lblTotal').text(sum);
// funcion suma por check
$( "input:checkbox").change(function(){
if($(this).is(':checked')){
$(this).parent().parent().find('td:last').addClass('suma2');
}else{
$(this).parent().parent().find('td:last').removeClass('suma2');
}
suma2Total();
})
function suma2Total(){
var sum2 = 0;
$('.suma2').each(function(x,y){
sum2 += parseInt($(this).text());
})
$('#lblTotal2').text(sum2);
}
});
you can do it on real device by run device in Debug mode
Click Debug->Simulate Location -> add .gpx file for your location during run time
An example:
if (!checkRadioArray(document.ExamEntry.level)) {
msg+="What is your level of entry? \n";
document.getElementById('entry').style.color="red";
result = false;
}
if(msg==""){
return result;
}
else{
alert(msg)
return result;
}
function Radio() {
var level = radio.value;
alert("Your level is: " + level + " \nIf this is not the level your taking then please choose another.")
}
function checkRadioArray(radioButtons) {
for(var r=0;r < radioButtons.length; r++) {
if (radioButtons[r].checked) {
return true;
}
}
return false;
}
var Data=[{"id": "name2", "label": "Quantity"}]
Pass the string variable into Json parse :
Objdata= Json.parse(Data);
Check this has everything you need
http://www.html5rocks.com/en/mobile/fullscreen/
The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.
<meta name="mobile-web-app-capable" content="yes">
It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.
var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');
To loop with each()
$("a.directions-link").each(function() {
var $this = $(this);
var _href = $this.attr("href");
$this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});
input
fields can be styled as you wish. So instead of zoom, you could have
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
}
EDIT:
You would have to add extra rules like this:
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
cursor: pointer;
-webkit-appearance: none;
appearance: none;
}
Check this fiddle http://jsfiddle.net/p36tqqyq/1/
UIImage(data:imageData,scale:1.0)
presuming the image's scale is 1.
In swift 4.2, use below code for get Data().
image.pngData()
You can use list comprehension:
res_list = [i[0] for i in rows]
This should make the trick
You can simply use "findViewHolderForAdapterPosition" method of recycler view and you will get a viewHolder object from that then typecast that viewholder into your adapter viewholder so you can directly access your viewholder's views
following is the sample code for kotlin
val viewHolder = recyclerView.findViewHolderForAdapterPosition(position)
val textview=(viewHolder as YourViewHolder).yourTextView
$http.delete
method doesn't accept request body.
You can try this workaround :
$http( angular.merge({}, config || {}, {
method : 'delete',
url : _url,
data : _data
}));
where in config
you can pass config data like headers etc.
How to throttle requestAnimationFrame to a specific frame rate
Demo throttling at 5 FPS: http://jsfiddle.net/m1erickson/CtsY3/
This method works by testing the elapsed time since executing the last frame loop.
Your drawing code executes only when your specified FPS interval has elapsed.
The first part of the code sets some variables used to calculate elapsed time.
var stop = false;
var frameCount = 0;
var $results = $("#results");
var fps, fpsInterval, startTime, now, then, elapsed;
// initialize the timer variables and start the animation
function startAnimating(fps) {
fpsInterval = 1000 / fps;
then = Date.now();
startTime = then;
animate();
}
And this code is the actual requestAnimationFrame loop which draws at your specified FPS.
// the animation loop calculates time elapsed since the last loop
// and only draws if your specified fps interval is achieved
function animate() {
// request another frame
requestAnimationFrame(animate);
// calc elapsed time since last loop
now = Date.now();
elapsed = now - then;
// if enough time has elapsed, draw the next frame
if (elapsed > fpsInterval) {
// Get ready for next frame by setting then=now, but also adjust for your
// specified fpsInterval not being a multiple of RAF's interval (16.7ms)
then = now - (elapsed % fpsInterval);
// Put your drawing code here
}
}
Wildcard works for me also, but I'd like to give a side note for those using directory variables. Always use slash for folder tree (not backslash), otherwise it will fail:
BASEDIR = ../..
SRCDIR = $(BASEDIR)/src
INSTALLDIR = $(BASEDIR)/lib
MODULES = $(wildcard $(SRCDIR)/*.cpp)
OBJS = $(wildcard *.o)
If you don't want to use anonymous types b/c let's say you're passing the object to another method, you can use the LoadWith load option to load associated data. It requires that your tables are associated either through foreign keys or in your Linq-to-SQL dbml model.
db.DeferredLoadingEnabled = false;
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<ObjectPermissions>(op => op.Pages)
db.LoadOptions = dlo;
var pageObject = from op in db.ObjectPermissions
select op;
// no join needed
Then you can call
pageObject.Pages.PageID
Depending on what your data looks like, you'd probably want to do this the other way around,
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Pages>(p => p.ObjectPermissions)
db.LoadOptions = dlo;
var pageObject = from p in db.Pages
select p;
// no join needed
var objectPermissionName = pageObject.ObjectPermissions.ObjectPermissionName;
The pure Groovy solutions that read the global env
variable don't print all environment variables (e. g. they are missing variables from the environment
block, from withEnv
context and most of the machine-specific variables from the OS). Using shell steps it is possible to get a more complete set, but that requires a node
context, which is not always wanted.
Here is a solution that uses the getContext
step to retrieve and print the complete set of environment variables, including pipeline parameters, for the current context.
Caveat: Doesn't work in Groovy sandbox. You can use it from a trusted shared library though.
def envAll = getContext( hudson.EnvVars )
echo envAll.collect{ k, v -> "$k = $v" }.join('\n')
While this question is quite old I just want to add another possibility of doing a merge while keeping keys.
Besides adding key/values to existing arrays using the +
sign you could do an array_replace
.
$a = array('foo' => 'bar', 'some' => 'string');
$b = array(42 => 'answer to the life and everything', 1337 => 'leet');
$merged = array_replace($a, $b);
The result will be:
Array
(
[foo] => bar
[some] => string
[42] => answer to the life and everything
[1337] => leet
)
Same keys will be overwritten by the latter array.
There is also an array_replace_recursive
, which do this for subarrays, too.
.col-xs-2{
background:#00f;
color:#FFF;
}
.col-half-offset{
margin-left:4.166666667%
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row" style="border: 1px solid red">
<div class="col-xs-4" id="p1">One</div>
<div class="col-xs-4 col-half-offset" id="p2">Two</div>
<div class="col-xs-4 col-half-offset" id="p3">Three</div>
<div>Test</div>
</div>
</div>
date("Y-m-d H:i:s", time() - date("Z"))
Full Outer join don't exist in mysql , you might need to use a combination of left and right join.
If using backbone.js (which contains url anchor
as route), url query string
may appear:
before url anchor
:
var url = 'http://example.com?a=1&b=3#routepath/subpath';
after url anchor
:
var url = 'http://example.com#routepath/subpath?a=1&b=3';
Solution:
window.location.href.replace(window.location.search, '');
// run as: 'http://example.com#routepath/subpath?a=1&b=3'.replace('?a=1&b=3', '');
import math
a = int(input("Enter the coefficients of a: "))
b = int(input("Enter the coefficients of b: "))
c = int(input("Enter the coefficients of c: "))
d = b**2-4*a*c # discriminant
if d < 0:
print ("This equation has no real solution")
elif d == 0:
x = (-b+math.sqrt(b**2-4*a*c))/2*a
print (("This equation has one solutions: "), x)
#add the extra () above or it does not show the answer just the text.
else:
x1 = (-b+math.sqrt((b**2)-(4*(a*c))))/(2*a)
x2 = (-b-math.sqrt((b**2)-(4*(a*c))))/(2*a)
print ("This equation has two solutions: ", x1, " or", x2)
Maybe use a combination with strtotime()
and date()
?
I needed to create a new client ID under APIs & Services -> Credentials -> Create credentials -> OAuth -> Other
Then I downloaded and used the client_secret.json with my command line program that is uploading to my youtube account. I was trying to use a Web App OAuth client ID which was giving me the redirect URI error in browser.
I want to extend @Jan answer:
It's seems, that Task Scheduler 1.0 API
uses C:\Windows\Tasks
folder for create and enumerate tasks (this example), while Task Scheduler 2.0 API
uses C:\Windows\System32\Tasks
to create and enumerate tasks (this example).
It's also seems, that windows console utility schtasks
and GUI utility taskschd.msc
uses Task Scheduler 2.0 API
.
P.S.
I found, that if task placed in C:\Windows\Tasks
and have not set AccountInformation
, then task won't be displayed in windows console and GUI schedulers. If you set AccountInformation
(even "" for SYSTEM account) and set flag TASK_FLAG_RUN_ONLY_IF_LOGGED_ON
- task will be displayed in all standard applications.
Open xampp application, then do the following:
go to: volumes,
click the [mount] button, and
finally click explore.
Updated Answer:
DynamoDB allows for specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.
For the use case in this question, you would want to use a global secondary index on the "CreatedAt" field.
For more on DynamoDB secondary indexes see the secondary index documentation
Original Answer:
DynamoDB does not allow indexed lookups on the range key only. The hash key is required such that the service knows which partition to look in to find the data.
You can of course perform a scan operation to filter by the date value, however this would require a full table scan, so it is not ideal.
If you need to perform an indexed lookup of records by time across multiple primary keys, DynamoDB might not be the ideal service for you to use, or you might need to utilize a separate table (either in DynamoDB or a relational store) to store item metadata that you can perform an indexed lookup against.
#For scheduling task execution
import schedule
import time
def job():
print("I'm working...")
schedule.every(1).minutes.do(job)
#schedule.every().hour.do(job)
#schedule.every().day.at("10:30").do(job)
#schedule.every(5).to(10).minutes.do(job)
#schedule.every().monday.do(job)
#schedule.every().wednesday.at("13:15").do(job)
#schedule.every().minute.at(":17").do(job)
while True:
schedule.run_pending()
time.sleep(1)
These are exactly the same. android:onClick
was added in API level 4 to make it easier, more Javascript-web-like, and drive everything from the XML. What it does internally is add an OnClickListener
on the Button, which calls your DoIt
method.
Here is what using a android:onClick="DoIt"
does internally:
Button button= (Button) findViewById(R.id.buttonId);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DoIt(v);
}
});
The only thing you trade off by using android:onClick
, as usual with XML configuration, is that it becomes a bit more difficult to add dynamic content (programatically, you could decide to add one listener or another depending on your variables). But this is easily defeated by adding your test within the DoIt
method.
You could use the {display: inline-flex;} this would produce this: inline-flex
If you want to change font size for all the text in a figure, you can use findall
to find all text handles, after which it's easy:
figureHandle = gcf;
%# make all text in the figure to size 14 and bold
set(findall(figureHandle,'type','text'),'fontSize',14,'fontWeight','bold')
There is a simple answer to this question which uses a dictionary of types to look up a lambda function. Here is how it might be used:
var ts = new TypeSwitch()
.Case((int x) => Console.WriteLine("int"))
.Case((bool x) => Console.WriteLine("bool"))
.Case((string x) => Console.WriteLine("string"));
ts.Switch(42);
ts.Switch(false);
ts.Switch("hello");
There is also a generalized solution to this problem in terms of pattern matching (both types and run-time checked conditions):
var getRentPrice = new PatternMatcher<int>()
.Case<MotorCycle>(bike => 100 + bike.Cylinders * 10)
.Case<Bicycle>(30)
.Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20)
.Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20)
.Default(0);
var vehicles = new object[] {
new Car { EngineType = EngineType.Diesel, Doors = 2 },
new Car { EngineType = EngineType.Diesel, Doors = 4 },
new Car { EngineType = EngineType.Gasoline, Doors = 3 },
new Car { EngineType = EngineType.Gasoline, Doors = 5 },
new Bicycle(),
new MotorCycle { Cylinders = 2 },
new MotorCycle { Cylinders = 3 },
};
foreach (var v in vehicles)
{
Console.WriteLine("Vehicle of type {0} costs {1} to rent", v.GetType(), getRentPrice.Match(v));
}
I use this code to daemonize my applications. It allows you start/stop/restart
the script using the following commands.
python myscript.py start
python myscript.py stop
python myscript.py restart
In addition to this I also have an init.d script for controlling my service. This allows you to automatically start the service when your operating system boots-up.
Here is a simple example to get your going. Simply move your code inside a class, and call it from the run
function inside MyDeamon
.
import sys
import time
from daemon import Daemon
class YourCode(object):
def run(self):
while True:
time.sleep(1)
class MyDaemon(Daemon):
def run(self):
# Or simply merge your code with MyDaemon.
your_code = YourCode()
your_code.run()
if __name__ == "__main__":
daemon = MyDaemon('/tmp/daemon-example.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
Upstart
If you are running an operating system that is using Upstart (e.g. CentOS 6) - you can also use Upstart to manage the service. If you use Upstart you can keep your script as is, and simply add something like this under /etc/init/my-service.conf
start on started sshd
stop on runlevel [!2345]
exec /usr/bin/python /opt/my_service.py
respawn
You can then use start/stop/restart to manage your service.
e.g.
start my-service
stop my-service
restart my-service
A more detailed example of working with upstart is available here.
Systemd
If you are running an operating system that uses Systemd (e.g. CentOS 7) you can take a look at the following Stackoverflow answer.
I have programmed an useful jQuery Plugin to create easily smart bubble popups with only a line of code in jQuery!
What You can do: - attach popups to any DOM element! - mouseover/mouseout events automatically managed! - set custom popups events! - create smart shadowed popups! (in IE too!) - choose popup’s style templates at runtime! - insert HTML messages inside popups! - set many options as: distances, velocity, delays, colors…
Popup’s shadows and colorized templates are fully supported by Internet Explorer 6+, Firefox, Opera 9+, Safari
You can download sources from http://plugins.jquery.com/project/jqBubblePopup
Basically the answer from Jani Hartikainen is right! I upvoted his answer. What was missing on my system (based on Ubuntu 15.04) was to enable PDO Extension in my php.ini
extension=pdo.so
extension=pdo_mysql.so
restart the webserver (e.g. with "sudo service apache2 restart") -> every fine :-)
To find where your current active php.ini file is located you can use phpinfo() or some other hints from here: https://www.ostraining.com/blog/coding/phpini-file/
You can use the username variable: %USERNAME%
For Makefile.PL-based distributions, use the INSTALL_BASE option when generating Makefiles:
perl Makefile.PL INSTALL_BASE=/mydir/perl
It's a linker problem. Include the static library path into your project.
For Qt Creator open the project file .pro
and add the following line:
LIBS += -L<path for boost libraries in the system> -lboost_system
In my case Ubuntu x86_64:
LIBS += -L/usr/lib/x86_64-linux-gnu -lboost_system
For Codeblocks, open up Settings->Compiler...->Linker
settings tab and add:
boost_system
to the Link libraries text widget and press OK button.
The best way to convert it to HashMap<String, Object>
is this:
HashMap<String, Object> result = new ObjectMapper().readValue(jsonString, new TypeReference<Map<String, Object>>(){}));
Cleaning the project worked for me, Build > clean project.
You can throw a HttpResponseException
HttpResponseMessage response =
this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "your message");
throw new HttpResponseException(response);
The code you have posted doesn't include a call to mysql_fetch_array()
. However, what is most likely going wrong is that you are issuing a query that returns an error message, in which case the return value from the query function is false
, and attempting to call mysql_fetch_array()
on it doesn't work (because boolean false
is not a mysql result object).
I am using Angular CLI 9.1.4 and all i did was just run:
ng add @angular/material
And all the angular material packages were installed and my package.json file was updated.
This is the easiest way to get that done.
For all the collections including map use: isEmpty
method which is there on these collection objects. But you have to do a null check before:
Map<String, String> map;
........
if(map!=null && !map.isEmpty())
......
I myself am trying to see how can I update RC4 to RC5 and thus I stumbled upon this entry and new approach to dynamic component creation still holds a bit of mystery to me, so I wont suggest anything on component factory resolver.
But, what I can suggest is a bit clearer approach to component creation on this scenario - just use switch in template that would create string editor or text editor according to some condition, like this:
<form [ngSwitch]="useTextarea">
<string-editor *ngSwitchCase="false" propertyName="'code'"
[entity]="entity"></string-editor>
<text-editor *ngSwitchCase="true" propertyName="'code'"
[entity]="entity"></text-editor>
</form>
And by the way, "[" in [prop] expression have a meaning, this indicates one way data binding, hence you can and even should omit those in case if you know that you do not need to bind property to variable.
Try setting the system default encoding as utf-8
at the start of the script, so that all strings are encoded using that.
Example -
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
The above should set the default encoding as utf-8
.
Try using
for i in a :
print(i[0])
i represents individual row in a.So,i[0] represnts the 1st element of each row.
I created a jsfiddle for you here: JSFiddle HTML & CSS Example
CSS
div.raspberry {
float: left;
margin: 2px;
}
div p {
text-align: center;
}
HTML (apply CSS above to get what you need)
<div>
<div class = "raspberry">
<img src="http://31.media.tumblr.com/tumblr_lwlpl7ZE4z1r8f9ino1_500.jpg" width="100" height="100" alt="Screen 2"/>
<p>Raspberry <br> For You!</p>
</div>
<div class = "raspberry">
<img src="http://31.media.tumblr.com/tumblr_lwlpl7ZE4z1r8f9ino1_500.jpg" width="100" height="100" alt="Screen 3"/>
<p>Raspberry <br> For You!</p>
</div>
<div class = "raspberry">
<img src="http://31.media.tumblr.com/tumblr_lwlpl7ZE4z1r8f9ino1_500.jpg" width="100" height="100" alt="Screen 3"/>
<p>Raspberry <br> For You!</p>
</div>
</div>
Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
Hope this could help someone else...
Advancing J. Costa's solution: You can make a global change to the table by putting this line of code:
[[UITableView appearance] setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
inside the first possible method (usually in AppDelegate
, in: application:didFinishLaunchingWithOptions:
method).
The suggestions don't work because they are for the standard MySQL driver, not for mysqli:
$this->db_link->error
contains the error if one did occur
Or
mysqli_error($this->db_link)
will work.
A more simplier way. I've tried this and it worked fine for me:
$(':input[type=submit]').prop('disabled', true);
Here's a reusable way of doing it (it's typescript but you can adapt it to js):
export function waitFor<T>(signal: Observable<any>) {
return (source: Observable<T>) =>
new Observable<T>(observer =>
signal.pipe(first())
.subscribe(_ =>
source.subscribe(observer)
)
);
}
and you can use it like any operator:
var two = someOtherObservable.pipe(waitFor(one), take(1));
It's basically an operator that defers the subscribe on the source observable until the signal observable emits the first event.
Here's a way that allows for ties for the cut-off score.
author_count = Author.objects.count()
cut_off_score = Author.objects.order_by('-score').values_list('score')[min(30, author_count)]
top_authors = Author.objects.filter(score__gte=cut_off_score).order_by('last_name')
You may get more than 30 authors in top_authors this way and the min(30,author_count)
is there incase you have fewer than 30 authors.
Html code for adding map
<div id="map" style="height:480px; width:360px;"></div>
css for loading map
.leaflet-div-icon
{
background-image: url('http://cloudmade.com/images/layout/cm-logo.png');
}
Logic for changing marker colour
var map = L.map('map').setView([51.5, -0.09], 13);
L.marker([51.49, -0.09]).addTo(map)
.bindPopup('Demo CSS3 popup. <br> Easily customizable.');
const myCustomColour = '#5f93ed'
const markerHtmlStyles = `
background-color: ${myCustomColour};
width: 15px;
height: 15px;
font-size:15px;
text-align:center;
display: block;
`
function thing(ct) {
return L.divIcon({
className: "box",
iconAnchor: [12, 25],
labelAnchor: [-6, 0],
popupAnchor: [0, -15],
html: `<span style="${markerHtmlStyles}" >M</span>`
})
}
L.marker([51.51, -0.09], {
icon: thing("hello")
}).addTo(map)
.bindPopup('divIcon CSS3 popup. <br> Supposed to be easily stylable.');
Oh, I found it. You use last instead of break
for my $entry (@array){
if ($string eq "text"){
last;
}
}
Method that works with arrays, and it works with objects too (beware, objects don't have a guaranteed order!).
I prefer this method the most, because original array is not modified.
// In case of array
var arr = [];
arr[3] = 'first';
arr[7] = 'last';
var firstElement;
for(var i in arr){
firstElement = arr[i];
break;
}
console.log(firstElement); // "first"
// In case of object
var obj = {
first: 'first',
last: 'last',
};
var firstElement;
for(var i in obj){
firstElement = obj[i];
break;
}
console.log(firstElement) // First;
Maybe this one can help:
function focus(el){_x000D_
el.focus();_x000D_
return el==document.activeElement;_x000D_
}
_x000D_
return value: true = success, false = failed
Reff: https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
You can query for the built-in session variables with SQL. To identify the version of DB2 on z/OS, you need the SYSIBM.VERSION variable. This will return the PRDID - the product identifier. You can look up the human-readable version in the Knowledge Center.
SELECT GETVARIABLE('SYSIBM.VERSION')
FROM SYSIBM.SYSDUMMY1;
-- for example, the above returns DSN10015
-- DSN10015 identifies DB2 10 in new-function mode (see second link above)
int intNumber = (int)uintNumber;
Depending on what kind of values you are expecting, you may want to check how big uintNumber is before doing the conversion. An int has a max value of about .5 of a uint.
Since recently, navigator.onLine
shows the same on all major browsers, and is thus useable.
if (navigator.onLine) {
// do things that need connection
} else {
// do things that don't need connection
}
The oldest versions that support this in the right way are: Firefox 41, IE 9, Chrome 14 and Safari 5.
Currently this will represent almost the whole spectrum of users, but you should always check what the users of your page have of capabilities.
Previous to FF 41, it would only show false
if the user put the browser manually in offline mode. In IE 8, the property was on the body
, instead of window
.
source: caniuse
I faced the same problem of brew command not found while installing Homebrew on mac BigSur with M1 processor.
I - Install XCode if it is not installed yet.
II - Select terminal.app in Finder.
III - RMB click on Terminal and select "Get Info"
IV - Select Open using Rosetta checkbox.
V - Close any open Terminal windows.
VI - Open a new Terminal window and install Hobebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
VII - Test Homebrew installation.
IIX - Uncheck Open using Rosetta checkbox.
In my Windows machine, I tried the solution of @nzrytmn i.e., Control Panel>Search Credentials>Select "ManageCredentials">modified new credentials under git option category corresponding to my username. And then,
Deleted current password:
git config --global --unset user.password
Added new password:
git config --global --add user.password "new_password"
And It worked for me.
So do it the old fashioned way and roll your own:
Map<String, Integer> instances = new HashMap<String, Integer>();
void add(String name) {
Integer value = instances.get(name);
if (value == null) {
value = new Integer(0);
instances.put(name, value);
}
instances.put(name, value++);
}
What is the difference between
sorted(list)
vslist.sort()
?
list.sort
mutates the list in-place & returns None
sorted
takes any iterable & returns a new list, sorted.sorted
is equivalent to this Python implementation, but the CPython builtin function should run measurably faster as it is written in C:
def sorted(iterable, key=None):
new_list = list(iterable) # make a new list
new_list.sort(key=key) # sort it
return new_list # return it
when to use which?
list.sort
when you do not wish to retain the original sort order
(Thus you will be able to reuse the list in-place in memory.) and when
you are the sole owner of the list (if the list is shared by other code
and you mutate it, you could introduce bugs where that list is used.)sorted
when you want to retain the original sort order or when you
wish to create a new list that only your local code owns.Can a list's original positions be retrieved after list.sort()?
No - unless you made a copy yourself, that information is lost because the sort is done in-place.
"And which is faster? And how much faster?"
To illustrate the penalty of creating a new list, use the timeit module, here's our setup:
import timeit
setup = """
import random
lists = [list(range(10000)) for _ in range(1000)] # list of lists
for l in lists:
random.shuffle(l) # shuffle each list
shuffled_iter = iter(lists) # wrap as iterator so next() yields one at a time
"""
And here's our results for a list of randomly arranged 10000 integers, as we can see here, we've disproven an older list creation expense myth:
Python 2.7
>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[3.75168503401801, 3.7473005310166627, 3.753129180986434]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[3.702025591977872, 3.709248117986135, 3.71071034099441]
Python 3
>>> timeit.repeat("next(shuffled_iter).sort()", setup=setup, number = 1000)
[2.797430992126465, 2.796825885772705, 2.7744789123535156]
>>> timeit.repeat("sorted(next(shuffled_iter))", setup=setup, number = 1000)
[2.675589084625244, 2.8019039630889893, 2.849375009536743]
After some feedback, I decided another test would be desirable with different characteristics. Here I provide the same randomly ordered list of 100,000 in length for each iteration 1,000 times.
import timeit
setup = """
import random
random.seed(0)
lst = list(range(100000))
random.shuffle(lst)
"""
I interpret this larger sort's difference coming from the copying mentioned by Martijn, but it does not dominate to the point stated in the older more popular answer here, here the increase in time is only about 10%
>>> timeit.repeat("lst[:].sort()", setup=setup, number = 10000)
[572.919036605, 573.1384446719999, 568.5923951]
>>> timeit.repeat("sorted(lst[:])", setup=setup, number = 10000)
[647.0584738299999, 653.4040515829997, 657.9457361929999]
I also ran the above on a much smaller sort, and saw that the new sorted
copy version still takes about 2% longer running time on a sort of 1000 length.
Poke ran his own code as well, here's the code:
setup = '''
import random
random.seed(12122353453462456)
lst = list(range({length}))
random.shuffle(lst)
lists = [lst[:] for _ in range({repeats})]
it = iter(lists)
'''
t1 = 'l = next(it); l.sort()'
t2 = 'l = next(it); sorted(l)'
length = 10 ** 7
repeats = 10 ** 2
print(length, repeats)
for t in t1, t2:
print(t)
print(timeit(t, setup=setup.format(length=length, repeats=repeats), number=repeats))
He found for 1000000 length sort, (ran 100 times) a similar result, but only about a 5% increase in time, here's the output:
10000000 100
l = next(it); l.sort()
610.5015971539542
l = next(it); sorted(l)
646.7786222379655
A large sized list being sorted with sorted
making a copy will likely dominate differences, but the sorting itself dominates the operation, and organizing your code around these differences would be premature optimization. I would use sorted
when I need a new sorted list of the data, and I would use list.sort
when I need to sort a list in-place, and let that determine my usage.
How about using grep -E
?
echo "This is 02G05 a test string 20-Jul-2012" | grep -Eo '[0-9]+G[0-9]+'
I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:
SELECT * FROM match WHERE id NOT IN
( SELECT id FROM email WHERE id IS NOT NULL) ;
SELECT
m.*
FROM
match m
LEFT OUTER JOIN email e ON
m.id = e.id
AND e.id IS NOT NULL
WHERE
e.id IS NULL
The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.
Detecting Browser and Its version
This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.
I have done few changes to detect browsers like Edge and UCBrowser
getBrowser = () => {
const userAgent = navigator.userAgent;
let browser = "unkown";
// Detect browser name
browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;
// detect browser version
switch (browser) {
case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
// IE version is mapped using trident version
// IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
default: return `unknown/0.0.0.0`;
}
}
browserVersion = (userAgent,regex) => {
return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}
console.log(getBrowser());
_x000D_
To send a message through TLS/SSL, you need to set Ssl of the SmtpClient class to true.
string to = "[email protected]";
string from = "[email protected]";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = @"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Send(message);
Solved on Laravel/Homestead (Vagrant Windows)
Edit Homestead.yaml
and increase memory from 2048 to 4096
vagrant up
vagrant ssh
Install Symfony with this line on the folder you choose (must be without files)
COMPOSER_MEMORY_LIMIT=-1 composer create-project symfony/website-skeleton . -s dev
The easiest way to do this is show hidden folders and then open the .SVN folder. You should see a zero KB file named "lock" deleting this will fix the problem
The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).
List implementations:
get add contains next remove(0) iterator.remove
ArrayList O(1) O(1) O(n) O(1) O(n) O(n)
LinkedList O(n) O(1) O(n) O(1) O(1) O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n) O(1) O(n) O(n)
Set implementations:
add contains next notes
HashSet O(1) O(1) O(h/n) h is the table capacity
LinkedHashSet O(1) O(1) O(1)
CopyOnWriteArraySet O(n) O(n) O(1)
EnumSet O(1) O(1) O(1)
TreeSet O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)
Map implementations:
get containsKey next Notes
HashMap O(1) O(1) O(h/n) h is the table capacity
LinkedHashMap O(1) O(1) O(1)
IdentityHashMap O(1) O(1) O(h/n) h is the table capacity
EnumMap O(1) O(1) O(1)
TreeMap O(log n) O(log n) O(log n)
ConcurrentHashMap O(1) O(1) O(h/n) h is the table capacity
ConcurrentSkipListMap O(log n) O(log n) O(1)
Queue implementations:
offer peek poll size
PriorityQueue O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1) O(1) O(1) O(n)
ArrayBlockingQueue O(1) O(1) O(1) O(1)
LinkedBlockingQueue O(1) O(1) O(1) O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue O(log n) O(1) O(log n) O(1)
LinkedList O(1) O(1) O(1) O(1)
ArrayDeque O(1) O(1) O(1) O(1)
LinkedBlockingDeque O(1) O(1) O(1) O(1)
The bottom of the javadoc for the java.util package contains some good links:
Solution Steps:
Unchecked "Automatically manage signing".
Select "Provisioning profile" in "Signing (Release)" section.
No signing certificate error will be show.
Then below the error has a "Manage Certificates" button. click the button.
OS X tends to prefix the system account names with "_"; you don't say what version of OS X you're using, but at least in 10.8 and 10.9 the _postgres user exists in a default install. Note that you won't be able to su
to this account (except as root), since it doesn't have a password. sudo -u _postgres
, on the other hand, should work fine.
If you want plain C exports, use a C project not C++. C++ DLLs rely on name-mangling for all the C++isms (namespaces etc...). You can compile your code as C by going into your project settings under C/C++->Advanced, there is an option "Compile As" which corresponds to the compiler switches /TP and /TC.
If you still want to use C++ to write the internals of your lib but export some functions unmangled for use outside C++, see the second section below.
What you really want to do is define a conditional macro in a header that will be included in all of the source files in your DLL project:
#ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec(dllexport)
#else
# define LIBRARY_API __declspec(dllimport)
#endif
Then on a function that you want to be exported you use LIBRARY_API
:
LIBRARY_API int GetCoolInteger();
In your library build project create a define LIBRARY_EXPORTS
this will cause your functions to be exported for your DLL build.
Since LIBRARY_EXPORTS
will not be defined in a project consuming the DLL, when that project includes the header file of your library all of the functions will be imported instead.
If your library is to be cross-platform you can define LIBRARY_API as nothing when not on Windows:
#ifdef _WIN32
# ifdef LIBRARY_EXPORTS
# define LIBRARY_API __declspec(dllexport)
# else
# define LIBRARY_API __declspec(dllimport)
# endif
#elif
# define LIBRARY_API
#endif
When using dllexport/dllimport you do not need to use DEF files, if you use DEF files you do not need to use dllexport/dllimport. The two methods accomplish the same task different ways, I believe that dllexport/dllimport is the recommended method out of the two.
If you need this to use LoadLibrary and GetProcAddress, or maybe importing from another language (i.e PInvoke from .NET, or FFI in Python/R etc) you can use extern "C"
inline with your dllexport to tell the C++ compiler not to mangle the names. And since we are using GetProcAddress instead of dllimport we don't need to do the ifdef dance from above, just a simple dllexport:
The Code:
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
EXTERN_DLL_EXPORT int getEngineVersion() {
return 1;
}
EXTERN_DLL_EXPORT void registerPlugin(Kernel &K) {
K.getGraphicsServer().addGraphicsDriver(
auto_ptr<GraphicsServer::GraphicsDriver>(new OpenGLGraphicsDriver())
);
}
And here's what the exports look like with Dumpbin /exports:
Dump of file opengl_plugin.dll
File Type: DLL
Section contains the following exports for opengl_plugin.dll
00000000 characteristics
49866068 time date stamp Sun Feb 01 19:54:32 2009
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 0001110E getEngineVersion = @ILT+265(_getEngineVersion)
2 1 00011028 registerPlugin = @ILT+35(_registerPlugin)
So this code works fine:
m_hDLL = ::LoadLibrary(T"opengl_plugin.dll");
m_pfnGetEngineVersion = reinterpret_cast<fnGetEngineVersion *>(
::GetProcAddress(m_hDLL, "getEngineVersion")
);
m_pfnRegisterPlugin = reinterpret_cast<fnRegisterPlugin *>(
::GetProcAddress(m_hDLL, "registerPlugin")
);
After iOS 7, this process has been simplified down to (swift 3.0):
// For registering nib files
tableView.register(UINib(nibName: "MyCell", bundle: Bundle.main), forCellReuseIdentifier: "cell")
// For registering classes
tableView.register(MyCellClass.self, forCellReuseIdentifier: "cell")
(Note) This is also achievable by creating the cells in the
.xib
or.stroyboard
files, as prototype cells. If you need to attach a class to them, you can select the cell prototype and add the corresponding class (must be a descendant ofUITableViewCell
, of course).
And later on, dequeued using (swift 3.0):
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell : UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "Hello"
return cell
}
The difference being that this new method not only dequeues the cell, it also creates if non-existant (that means that you don't have to do if (cell == nil)
shenanigans), and the cell is ready to use just as in the example above.
(Warning)
tableView.dequeueReusableCell(withIdentifier:for:)
has the new behavior, if you call the other one (withoutindexPath:
) you get the old behavior, in which you need to check fornil
and instance it yourself, notice theUITableViewCell?
return value.
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as? MyCellClass
{
// Cell be casted properly
cell.myCustomProperty = true
}
else
{
// Wrong type? Wrong identifier?
}
And of course, the type of the associated class of the cell is the one you defined in the .xib file for the UITableViewCell
subclass, or alternatively, using the other register method.
Ideally, your cells have been already configured in terms of appearance and content positioning (like labels and image views) by the time you registered them, and on the cellForRowAtIndexPath
method you simply fill them in.
class MyCell : UITableViewCell
{
// Can be either created manually, or loaded from a nib with prototypes
@IBOutlet weak var labelSomething : UILabel? = nil
}
class MasterViewController: UITableViewController
{
var data = ["Hello", "World", "Kinda", "Cliche", "Though"]
// Register
override func viewDidLoad()
{
super.viewDidLoad()
tableView.register(MyCell.self, forCellReuseIdentifier: "mycell")
// or the nib alternative
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return data.count
}
// Dequeue
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "mycell", for: indexPath) as! MyCell
cell.labelSomething?.text = data[indexPath.row]
return cell
}
}
And of course, this is all available in ObjC with the same names.
You can get the bin path by AppDomain.CurrentDomain.RelativeSearchPath
It can be done with two simple lines in a batch file: write a temporary .vbs
file in the %temp%
folder and call it:
echo WScript.Sleep(5000) >"%temp%\sleep.vbs"
cscript "%temp%\sleep.vbs"
You need an Oracle Client: http://www.oracle.com/technology/oramag/oracle/08-nov/o68odpnet.html
This is not a matter of accuracy, nor is it a matter of precision. It is a matter of meeting the expectations of humans who use base 10 for calculations instead of base 2. For example, using doubles for financial calculations does not produce answers that are "wrong" in a mathematical sense, but it can produce answers that are not what is expected in a financial sense.
Even if you round off your results at the last minute before output, you can still occasionally get a result using doubles that does not match expectations.
Using a calculator, or calculating results by hand, 1.40 * 165 = 231 exactly. However, internally using doubles, on my compiler / operating system environment, it is stored as a binary number close to 230.99999... so if you truncate the number, you get 230 instead of 231. You may reason that rounding instead of truncating would have given the desired result of 231. That is true, but rounding always involves truncation. Whatever rounding technique you use, there are still boundary conditions like this one that will round down when you expect it to round up. They are rare enough that they often will not be found through casual testing or observation. You may have to write some code to search for examples that illustrate outcomes that do not behave as expected.
Assume you want to round something to the nearest penny. So you take your final result, multiply by 100, add 0.5, truncate, then divide the result by 100 to get back to pennies. If the internal number you stored was 3.46499999.... instead of 3.465, you are going to get 3.46 instead 3.47 when you round the number to the nearest penny. But your base 10 calculations may have indicated that the answer should be 3.465 exactly, which clearly should round up to 3.47, not down to 3.46. These kinds of things happen occasionally in real life when you use doubles for financial calculations. It is rare, so it often goes unnoticed as an issue, but it happens.
If you use base 10 for your internal calculations instead of doubles, the answers are always exactly what is expected by humans, assuming no other bugs in your code.
Some of the other answers would have poor performance on very large arrays, because methods like removeObject:
and removeObjectsInArray:
involve doing a linear search of the receiver, which is a waste because you already know where the object is. Also, any call to removeObjectAtIndex:
will have to copy values from the index to the end of the array up by one slot at a time.
More efficient would be the following:
NSMutableArray *array = ...
NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];
for (id object in array) {
if (! shouldRemove(object)) {
[itemsToKeep addObject:object];
}
}
[array setArray:itemsToKeep];
Because we set the capacity of itemsToKeep
, we don't waste any time copying values during a resize. We don't modify the array in place, so we are free to use Fast Enumeration. Using setArray:
to replace the contents of array
with itemsToKeep
will be efficient. Depending on your code, you could even replace the last line with:
[array release];
array = [itemsToKeep retain];
So there isn't even a need to copy values, only swap a pointer.
Method 1 :
var stringValue = "true";
var boolValue = (/true/i).test(stringValue) //returns true
Method 2 :
var stringValue = "true";
var boolValue = (stringValue =="true"); //returns true
Method 3 :
var stringValue = "true";
var boolValue = JSON.parse(stringValue); //returns true
Method 4 :
var stringValue = "true";
var boolValue = stringValue.toLowerCase() == 'true'; //returns true
Method 5 :
var stringValue = "true";
var boolValue = getBoolean(stringValue); //returns true
function getBoolean(value){
switch(value){
case true:
case "true":
case 1:
case "1":
case "on":
case "yes":
return true;
default:
return false;
}
}
source: http://codippa.com/how-to-convert-string-to-boolean-javascript/
Had the same issue with arrays, here is how to do it if you're manipulating arrays too :
array_name="ARRAY_NAME"
ARRAY_NAME=("Val0" "Val1" "Val2")
ARRAY=$array_name[@]
echo "ARRAY=${ARRAY}"
ARRAY=("${!ARRAY}")
echo "ARRAY=${ARRAY[@]}"
echo "ARRAY[0]=${ARRAY[0]}"
echo "ARRAY[1]=${ARRAY[1]}"
echo "ARRAY[2]=${ARRAY[2]}"
This will output :
ARRAY=ARRAY_NAME[@]
ARRAY=Val0 Val1 Val2
ARRAY[0]=Val0
ARRAY[1]=Val1
ARRAY[2]=Val2
The other answers lack a concrete example, so here it goes:
Given the following People table:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Thomas | More | 1478
Thomas | Jefferson | 1826
If you execute the query below:
SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC
The result set will look like this:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | More | 1478
Thomas | Jefferson | 1826
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
To plot multiple graphs on the same figure you will have to do:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.
If you are like me who has tried all the above solutions and still your problem is not solved, I have a got a great solution for you that works like a charm. First I want clarify few things about some of solutions mentioned above.
There are many answers recommend to use: Array.prototype.push(a, b)
. It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.
See What is the most efficient way to concatenate N arrays? for more details.
>>> from operator import itemgetter
>>> data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
>>> sorted(data,key=itemgetter(1))
[('abc', 121), ('abc', 148), ('abc', 221), ('abc', 231)]
IMO using itemgetter
is more readable in this case than the solution by @cheeken. It is
also faster since almost all of the computation will be done on the c
side (no pun intended) rather than through the use of lambda
.
>python -m timeit -s "from operator import itemgetter; data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=itemgetter(1))"
1000000 loops, best of 3: 1.22 usec per loop
>python -m timeit -s "data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=lambda x: x[1])"
1000000 loops, best of 3: 1.4 usec per loop
Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values
GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();
Remember before you merge you need to update the tag, it's quite different from branches (git pull origin tag_name
won't update your local tags). Thus, you need the following command:
git fetch --tags origin
Then you can perform git merge tag_name
to merge the tag onto a branch.
Following is the regex expression to validate the IP-Address.
^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$
Taken from above:
from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435
For a two-tailed test:
Import numpy as np
z = 1.96
p_value = 2 * norm.cdf(-np.abs(z))
0.04999579029644087
Yes, this is possible.
<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
<input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>
<input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>
<input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>
<input type="submit" name="submit" value="Search" />
</form>
By adding onchange="document.getElementById('formName').submit()"
to each checkbox, you'll submit any time a checkbox is changed.
If you're OK with jQuery, it's even easier (and unobtrusive):
$(document).ready(function(){
$("#formname").on("change", "input:checkbox", function(){
$("#formname").submit();
});
});
For any number of checkboxes in your form, when the "change" event happens, the form is submitted. This will even work if you dynamically create more checkboxes thanks to the .on()
method.
Here's my code Example for if..else..if
which do the following
Prompt user for Process Name
If the process name is invalid
Then it's write to user
Error : The Processor above doesn't seem to be exist
if the process name is services
Then it's write to user
Error : You can't kill the Processor above
if the process name is valid and not services
Then it's write to user
the process has been killed via taskill
so i called it Process killer.bat
Here's my Code:
@echo off
:Start
Rem preparing the batch
cls
Title Processor Killer
Color 0B
Echo Type Processor name to kill It (Without ".exe")
set /p ProcessorTokill=%=%
:tasklist
tasklist|find /i "%ProcessorTokill%.exe">nul & if errorlevel 1 (
REM check if the process name is invalid
Cls
Title %ProcessorTokill% Not Found
Color 0A
echo %ProcessorTokill%
echo Error : The Processor above doesn't seem to be exist
) else if %ProcessorTokill%==services (
REM check if the process name is services and doesn't kill it
Cls
Color 0c
Title Permission denied
echo "%ProcessorTokill%.exe"
echo Error : You can't kill the Processor above
) else (
REM if the process name is valid and not services
Cls
Title %ProcessorTokill% Found
Color 0e
echo %ProcessorTokill% Found
ping localhost -n 2 -w 1000>nul
echo Killing %ProcessorTokill% ...
taskkill /f /im %ProcessorTokill%.exe /t>nul
echo %ProcessorTokill% Killed...
)
pause>nul
REM If else if Template
REM if thing1 (
REM Command here 2 !
REM ) else if thing2 (
REM command here 2 !
REM ) else (
REM command here 3 !
REM )
/* I have done it this way, and also tested it */
Step 1 = Register custom cell class (in case of prototype cell in table) or nib (in case of custom nib for custom cell) for table like this in viewDidLoad method:
[self.yourTableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCell"];
OR
[self.yourTableView registerNib:[UINib nibWithNibName:@"CustomTableViewCell" bundle:nil] forCellReuseIdentifier:@"CustomCell"];
Step 2 = Use UITableView's "dequeueReusableCellWithIdentifier: forIndexPath:" method like this (for this, you must register class or nib) :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell" forIndexPath:indexPath];
cell.imageViewCustom.image = nil; // [UIImage imageNamed:@"default.png"];
cell.textLabelCustom.text = @"Hello";
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// retrive image on global queue
UIImage * img = [UIImage imageWithData:[NSData dataWithContentsOfURL: [NSURL URLWithString:kImgLink]]];
dispatch_async(dispatch_get_main_queue(), ^{
CustomTableViewCell * cell = (CustomTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
// assign cell image on main thread
cell.imageViewCustom.image = img;
});
});
return cell;
}
This section of the boto3 documentation is helpful.
Here's what worked for me:
session = boto3.Session(profile_name='dev')
client = session.client('cloudfront')
Switch Build Configuration back to Debug mode or turn on Build Active Architecture Only for both Debug and Release mode. The reason is your library/framework doesn't support new Simulator architecture ARM64 (run on Mac with Apple Silicon processor)
I'm using below excel file url: https://github.com/inventorbala/Sample-Excel-files/blob/master/sample-excel-files.xlsx
Output:
Array
(
[0] => Array
(
[store_id] => 3716
[employee_uid] => 664368
[opus_id] => zh901j
[item_description] => PRE ATT $75 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => X2MBV1DJKSLQW
[opus_invoice_num] => O3716IN3409
[customer_name] => BILL PHILLIPS
[mobile_num] => 4052380136
[opus_amount] => 75
[rq4_amount] => 0
[difference] => -75
[ocomment] => Re-Upload: We need RQ4 transaction for October. If you're unable to provide the October invoice, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[1] => Array
(
[store_id] => 2710
[employee_uid] => 75899
[opus_id] => dc288t
[item_description] => PRE ATT $50 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => XJ90419JKT9R9
[opus_invoice_num] => M2710IN868
[customer_name] => CALEB MENDEZ
[mobile_num] => 6517672079
[opus_amount] => 50
[rq4_amount] => 0
[difference] => -50
[ocomment] => No Response. Re-Upload
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[2] => Array
(
[store_id] => 0136
[employee_uid] => 70167
[opus_id] => fv766x
[item_description] => PRE ATT $50 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => XQ57316JKST1V
[opus_invoice_num] => GONZABP25622
[customer_name] => FAUSTINA CASTILLO
[mobile_num] => 8302638628
[opus_amount] => 100
[rq4_amount] => 50
[difference] => -50
[ocomment] => Re-Upload: We have been charged in opus for $100. Provide RQ4 invoice number for remaining amount
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[3] => Array
(
[store_id] => 3264
[employee_uid] => 23723
[opus_id] => aa297h
[item_description] => PRE ATT $25 PNLS 90EXP
[opus_transaction_date] => 2019-10-19
[opus_transaction_num] => XR1181HJKW9MP
[opus_invoice_num] => C3264IN1588
[customer_name] => SOPHAT VANN
[mobile_num] => 9494668372
[opus_amount] => 70
[rq4_amount] => 25
[difference] => -45
[ocomment] => No Response. Re-Upload
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[4] => Array
(
[store_id] => 4166
[employee_uid] => 568494
[opus_id] => ab7598
[item_description] => PRE ATT $40 RTR
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => X8F58P3JL2RFU
[opus_invoice_num] => I4166IN2481
[customer_name] => KELLY MC GUIRE
[mobile_num] => 6189468180
[opus_amount] => 40
[rq4_amount] => 0
[difference] => -40
[ocomment] => Re-Upload: The invoice number that you provided (I4166IN2481) belongs to September transaction. We need RQ4 transaction for October. If you're unable to provide the October invoice, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[5] => Array
(
[store_id] => 4508
[employee_uid] => 552502
[opus_id] => ec850x
[item_description] => $30 RTR
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XPL7M1BJL1W5D
[opus_invoice_num] => M4508IN6024
[customer_name] => PREPAID CUSTOMER
[mobile_num] => 6019109730
[opus_amount] => 30
[rq4_amount] => 0
[difference] => -30
[ocomment] => Re-Upload: The invoice number you provided (M4508IN7217) belongs to a different phone number. We need RQ4 transaction for the phone number in question. If you're unable to provide the RQ4 invoice for this transaction, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[6] => Array
(
[store_id] => 3904
[employee_uid] => 35818
[opus_id] => tj539j
[item_description] => PRE $45 PAYG PINLESS REFILL
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XM1PZQSJL215F
[opus_invoice_num] => N3904IN1410
[customer_name] => DORTHY JONES
[mobile_num] => 3365982631
[opus_amount] => 90
[rq4_amount] => 45
[difference] => -45
[ocomment] => Re-Upload: Please email the details to Treasury and confirm
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[7] => Array
(
[store_id] => 1820
[employee_uid] => 59883
[opus_id] => cb9406
[item_description] => PRE ATT $25 PNLS 90EXP
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XTBJO14JL25OE
[opus_invoice_num] => SEVIEIN19013
[customer_name] => RON NELSON
[mobile_num] => 8653821076
[opus_amount] => 25
[rq4_amount] => 5
[difference] => -20
[ocomment] => Re-Upload: We have been charged in opus for $25. Provide RQ4 invoice number for remaining amount
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[8] => Array
(
[store_id] => 0178
[employee_uid] => 572547
[opus_id] => ms5674
[item_description] => PRE $45 PAYG PINLESS REFILL
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XT29916JL4S69
[opus_invoice_num] => T0178BP1590
[customer_name] => GABRIEL LONGORIA JR
[mobile_num] => 4322133450
[opus_amount] => 45
[rq4_amount] => 0
[difference] => -45
[ocomment] => Re-Upload: Please email the details to Treasury and confirm
[mark_delete] => 0
[upload_date] => 2019-10-22
)
[9] => Array
(
[store_id] => 2180
[employee_uid] => 7842
[opus_id] => lm854y
[item_description] => $30 RTR
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XC9U712JL4LA4
[opus_invoice_num] => KETERIN1836
[customer_name] => PETE JABLONSKI
[mobile_num] => 9374092680
[opus_amount] => 30
[rq4_amount] => 40
[difference] => 10
[ocomment] => Re-Upload: Credit the remaining balance to customers account in OPUS and email confirmation to Treasury
[mark_delete] => 0
[upload_date] => 2019-10-22
)
.
.
.
[63] => Array
(
[store_id] => 0175
[employee_uid] => 33738
[opus_id] => ph5953
[item_description] => PRE ATT $40 RTR
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XE5N31DJL51RA
[opus_invoice_num] => T0175IN4563
[customer_name] => WILLIE TAYLOR
[mobile_num] => 6822701188
[opus_amount] => 40
[rq4_amount] => 50
[difference] => 10
[ocomment] => Re-Upload: Credit the remaining balance to customers account in OPUS and email confirmation to Treasury
[mark_delete] => 0
[upload_date] => 2019-10-22
)
)
You can get it with:
var html = new System.Net.WebClient().DownloadString(siteUrl)
querySelector
can be a complete CSS(3)-Selector with IDs and Classes and Pseudo-Classes together like this:
'#id.class:pseudo'
// or
'tag #id .class .class.class'
with getElementsByClassName
you can just define a class
'class'
with getElementById
you can just define an id
'id'
You can use System.IO.Path.GetFileName
to do this.
E.g.,
string[] files = Directory.GetFiles(dir);
foreach(string file in files)
Console.WriteLine(Path.GetFileName(file));
While you could use FileInfo
, it is much more heavyweight than the approach you are already using (just retrieving file paths). So I would suggest you stick with GetFiles
unless you need the additional functionality of the FileInfo
class.
Instead of:
var host = req.get('host');
var origin = req.get('origin');
you can also use:
var host = req.headers.host;
var origin = req.headers.origin;
Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.
System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");
should be:
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
You could do this (ugly but it works):
INSERT INTO dbo.MyTable (ID, Name)
select * from
(
select 123, 'Timmy'
union all
select 124, 'Jonny'
union all
select 125, 'Sally'
...
) x