I had some problems with this. It seemed to be a file permission issue somewhere in the app - not the .env-file.
I had to - stop my docker - use chown to set owning-rights to my own user for the whole project - start docker again
This time it worked.
You need to first add using Microsoft.Win32;
to your code page.
Then you can begin to use the Registry
classes:
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
{
if (key != null)
{
Object o = key.GetValue("Version");
if (o != null)
{
Version version = new Version(o as String); //"as" because it's REG_SZ...otherwise ToString() might be safe(r)
//do what you like with version
}
}
}
}
catch (Exception ex) //just for demonstration...it's always best to handle specific exceptions
{
//react appropriately
}
BEWARE: unless you have administrator access, you are unlikely to be able to do much in LOCAL_MACHINE
. Sometimes even reading values can be a suspect operation without admin rights.
Just ran into the same problem. Installing the .NET framework on the target machine solved the problem.
Better yet, make sure all required dependencies are present in the machine where the code will be running.
After instantiating the connection, open it.
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
SQLConnection.Open()
Also, avoid building SQL statements by just appending strings. It's better if you use parameters, that way you win on performance, your program is not prone to SQL injection attacks and your program is more stable. For example:
str_carSql = "insert into members_car
(car_id, member_id, model, color, chassis_id, plate_number, code)
values
(@id,@m_id,@model,@color,@ch_id,@pt_num,@code)"
And then you do this:
sqlCommand.Parameters.AddWithValue("@id",TextBox20.Text)
sqlCommand.Parameters.AddWithValue("@m_id",TextBox23.Text)
' And so on...
Then you call:
sqlCommand.ExecuteNonQuery()
A small variation on Husky's idea that I use. Make a file called 'globals' (or whatever you like) and then define multiple classes in it, as such:
#globals.py
class dbinfo : # for database globals
username = 'abcd'
password = 'xyz'
class runtime :
debug = False
output = 'stdio'
Then, if you have two code files c1.py and c2.py, both can have at the top
import globals as gl
Now all code can access and set values, as such:
gl.runtime.debug = False
print(gl.dbinfo.username)
People forget classes exist, even if no object is ever instantiated that is a member of that class. And variables in a class that aren't preceded by 'self.' are shared across all instances of the class, even if there are none. Once 'debug' is changed by any code, all other code sees the change.
By importing it as gl, you can have multiple such files and variables that lets you access and set values across code files, functions, etc., but with no danger of namespace collision.
This lacks some of the clever error checking of other approaches, but is simple and easy to follow.
Right Click the Project in Solution Explorer and click Manage NuGet Packages
Search for MySql.Data package, when you find it click on Install
Here is the sample controller which connects to MySql database using the mysql package. We mainly make use of MySqlConnection connection object.
public class HomeController : Controller
{
public ActionResult Index()
{
List<employeemodel> employees = new List<employeemodel>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT EmployeeId, Name, Country FROM Employees";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
employees.Add(new EmployeeModel
{
EmployeeId = Convert.ToInt32(sdr["EmployeeId"]),
Name = sdr["Name"].ToString(),
Country = sdr["Country"].ToString()
});
}
}
con.Close();
}
}
return View(employees);
}
}
This is an older question, but I found it yesterday while struggling with getting the MySQL Connector reference working properly on examples I'd found on the web. I'm working with VS 2010 on Win7 64 bit but have to work with .NET 3.5.
As others have stated, you need to download the .Net & Mono versions (I don't know why this is true, but it's what I've found works). The link to the connectors is given above in the earlier answers.
m2e 0.13 introduce a m2e connectors and m2e Market Place to extend m2e features. It's like the old m2e-extras repository.
You can access the m2e market place from the preferences: Preferences>Maven>Discovery>Open Catalog. Installing WTP integration solved most plugin issues for me.
Your question in somewhat confusing in that that you don't explain what you mean by "current element".
If you have multiple forms on a page with all kinds of input elements and a button of type "submit", then hitting "enter" upon filling any of it's fields will trigger submission of that form. You don't need any Javascript there.
But if you have multiple "submit" buttons on a form and no other inputs (e.g. "edit row" and/or "delete row" buttons in table), then the line you posted could be the way to do it.
Another way (no Javascript needed) could be to give different values to all your buttons (that are of type "submit"). Like this:
<form action="...">
<input type="hidden" name="rowId" value="...">
<button type="submit" name="myaction" value="edit">Edit</button>
<button type="submit" name="myaction" value="delete">Delete</button>
</form>
When you click a button only the form containing the button will be submitted, and only the value of the button you hit will be sent (along other input values).
Then on the server you just read the value of the variable "myaction" and decide what to do.
Log location:
${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log
Get log as a text and save to workspace:
cat ${JENKINS_HOME}/jobs/${JOB_NAME}/builds/${BUILD_NUMBER}/log >> log.txt
Hi its quite simple to make switch between buttons using switch case:-
package com.example.browsebutton;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int id=v.getId();
switch(id) {
case R.id.button1:
Toast.makeText(getBaseContext(), "btn1", Toast.LENGTH_LONG).show();
//Your Operation
break;
case R.id.button2:
Toast.makeText(getBaseContext(), "btn2", Toast.LENGTH_LONG).show();
//Your Operation
break;
}
}}
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
Simply use the Get-Content
and Set-Content
cmdlets:
Get-Content inputFile1.txt, inputFile2.txt | Set-Content joinedFile.txt
You can concatenate more than two files with this style, too.
If the source files are named similarly, you can use wildcards:
Get-Content inputFile*.txt | Set-Content joinedFile.txt
Note 1: PowerShell 5 and older versions allowed this to be done more concisely using the aliases cat
and sc
for Get-Content
and Set-Content
respectively. However, these aliases are problematic because cat
is a system command in *nix systems, and sc
is a system command in Windows systems - therefore using them is not recommended, and in fact sc
is no longer even defined as of PowerShell Core (v7). The PowerShell team recommends against using aliases in general.
Note 2: Be careful with wildcards - if you try to output to examples.txt
(or similar that matches the pattern), PowerShell will get into an infinite loop! (I just tested this.)
Note 3: Outputting to a file with >
does not preserve character encoding! This is why using Set-Content
is recommended.
Using:
@ComponentScan
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
//do your ReconTool stuff
}
}
will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.
Using maven just use mvn spring-boot:run
while in gradle it would be gradle bootRun
An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner
. That would look like:
@Component
public class ReconTool implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
//implement your business logic here
}
}
Check out this guide from Spring's official guide repository.
The full Spring Boot documentation can be found here
line=$(head -1 file)
Will work fine. (As previous answer). But
line=$(read -r FIRSTLINE < filename)
will be marginally faster as read
is a built-in bash command.
If you are linking to many files, create a whitelist, and then use sendFile():
app.get('/npm/:pkg/:file', (req, res) => {
const ok = ['jquery','bootstrap','interactjs'];
if (!ok.includes(req.params.pkg)) res.status(503).send("Not Permitted.");
res.sendFile(__dirname + `/node_modules/${req.params.pkg}/dist/${req.params.file}`);
});
For example, You can then safely link to /npm/bootstrap/bootsrap.js, /npm/bootstrap/bootsrap.css, etc.
As an aside, I would love to know if there was a way to whitelist using express.static
Using org.json
If you have a String containing JSON format text, then you can get JSON Object by following steps:
String jsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
Now to access the phonetype
Sysout.out.println(jsonObject.getString("phonetype"));
Take a look at that : http://davidwalsh.name/detect-android
JavaScript:
var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
// Do something!
// Redirect to Android-site?
window.location = 'http://android.davidwalsh.name';
}
PHP:
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
header('Location: http://android.davidwalsh.name');
exit();
}
Edit : As pointed out in some comments, this will work in 99% of the cases, but some edge cases are not covered. If you need a much more advanced and bulletproofed solution in JS, you should use platform.js : https://github.com/bestiejs/platform.js
Expanding on brettdj's answer, in order to parse disjoint embedded digits into separate numbers:
Sub TestNumList()
Dim NumList As Variant 'Array
NumList = GetNums("34d1fgd43g1 dg5d999gdg2076")
Dim i As Integer
For i = LBound(NumList) To UBound(NumList)
MsgBox i + 1 & ": " & NumList(i)
Next i
End Sub
Function GetNums(ByVal strIn As String) As Variant 'Array of numeric strings
Dim RegExpObj As Object
Dim NumStr As String
Set RegExpObj = CreateObject("vbscript.regexp")
With RegExpObj
.Global = True
.Pattern = "[^\d]+"
NumStr = .Replace(strIn, " ")
End With
GetNums = Split(Trim(NumStr), " ")
End Function
This might be an old topic but in my case it was the layout
value of css contain
property of the parent element that was causing the issue. I am using a framework for hybrid mobile that use this contain
property in most of their component.
For example:
.parentEl {
contain: size style layout;
}
.parentEl .childEl {
position: fixed;
top: 0;
left: 0;
}
Just remove the layout
value of contain
property and the fixed content should work!
.parentEl {
contain: size style;
}
my jQuery powered solution is below :)
Text Element:
<asp:TextBox ID="txtTextBox" ClientIDMode="Static" onkeypress="return EnterEvent(event);" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmitButton" ClientIDMode="Static" OnClick="btnSubmitButton_Click" runat="server" Text="Submit Form" />
Javascript behind:
<script type="text/javascript" language="javascript">
function fnCheckValue() {
var myVal = $("#txtTextBox").val();
if (myVal == "") {
alert("Blank message");
return false;
}
else {
return true;
}
}
function EnterEvent(e) {
if (e.keyCode == 13) {
if (fnCheckValue()) {
$("#btnSubmitButton").trigger("click");
} else {
return false;
}
}
}
$("#btnSubmitButton").click(function () {
return fnCheckValue();
});
</script>
ACID properties are very old and important concept of database theory. I know that you can find lots of posts on this topic, but still I would like to start share answer on this because this is very important topic of RDBMS.
Database System plays with lots of different types of transactions where all transaction has certain characteristic. This characteristic is known ACID Properties. ACID Properties take grantee for all database transactions to accomplish all tasks.
Atomicity : Either commit all or nothing.
Consistency : Make consistent record in terms of validate all rule and constraint of transaction.
Isolation : Make sure that two transaction is unaware to each other.
Durability : committed data stored forever. Reference taken from this article:
I wrote a plugin that can fire callbacks when images have loaded in elements, or fire once per image loaded.
It is similar to $(window).load(function() { .. })
, except it lets you define any selector to check. If you only want to know when all images in #content
(for example) have loaded, this is the plugin for you.
It also supports loading of images referenced in the CSS, such as background-image
, list-style-image
, etc.
$('selector').waitForImages(function() {
alert('All images are loaded.');
});
More documentation is available on the GitHub page.
If it were me, I'd probably boil it down to a single selector:
$('someTableSelector tr:not(:first)').remove();
I found that when testing native browser functions in IE8, using toString
, instanceof
, and typeof
did not work. Here is a method that works fine in IE8 (as far as I know):
function isFn(f){
return !!(f && f.call && f.apply);
}
//Returns true in IE7/8
isFn(document.getElementById);
Alternatively, you can check for native functions using:
"getElementById" in document
Though, I have read somewhere that this will not always work in IE7 and below.
As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]}
are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".
{16{a[15]}}
is the same as
{
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}
In bit-blasted form,
assign result = {{16{a[15]}}, {a[15:0]}};
is the same as:
assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];
This would use less memory, but probably take longer
int count = 0;
string line;
TextReader reader = new StreamReader("file.txt");
while ((line = reader.ReadLine()) != null)
{
count++;
}
reader.Close();
Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).
there is some change since the 0.16 so here how i did,
import in the pubspec.yaml
dependencies:
flutter:
sdk: flutter
intl: ^0.16.1
then use
txdate= DateTime.now()
DateFormat.yMMMd().format(txdate)
rcedit is relative new and works well from the command line: https://github.com/atom/rcedit
$ rcedit "path-to-exe-or-dll" --set-version-string "Comments" "This is an exe"
$ rcedit "path-to-exe-or-dll" --set-file-version "10.7"
$ rcedit "path-to-exe-or-dll" --set-product-version "10.7"
There's also an NPM module which wraps it from JavaScript and a Grunt task in case you're using Grunt.
I had the same problem and Andrew is correct. Check your classpath variable "M2_REPO". It probably points to an invalid location of your local maven repo.
In my case I was using mvn eclipse:eclipse
on the command line and this plugin was setting the M2_REPO classpath variable. Eclipse couldn't find my maven settings.xml in my home directory and as a result was incorrectly the M2_REPO classpath variable. My solution was to restart eclipse and it picked up my settings.xml and removed the red exclamation on my projects.
I got some more information from this guy: http://www.mkyong.com/maven/how-to-configure-m2_repo-variable-in-eclipse-ide/
Assuming you are dealing with a JSON-string in the input, you can parse it using the json
package, see the documentation.
In the specific example you posted you would need
x = json.loads("""{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']
And I simply got this error because I used a totally different DocumentRoot directory.
My main DocumentRoot was the default /var/www/html
and on the VirtualHost I used /sites/example.com
I have created a link on /var/www/html/example.com
(to /sites/example.com
).
DocumentRoot was set to /var/www/html/example.com
It worked like a charm.
Make sure that types in the function declaration are declared first.
/* start of the header file */
.
.
.
struct intr_frame{...}; //must be first!
.
.
.
void kill (struct intr_frame *);
.
.
.
/* end of the header file */
width="100" height="100"
in the svg file then add this x="0px" y="0px" width="100" height="100" viewBox="0 0 100 100"
while keeping the already defined width="100" height="100"
. img
so you could then do this: img{height: 20px; width: 20px;}
and the image will scale. $ npm uninstall -g angular-cli
$ npm cache clean
$ npm install -g angular-cli
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
The INSERT INTO Statement
The INSERT INTO statement is used to insert a new row in a table.
SQL INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
INSERT INTO table_name
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
For those who are not PYTHON expert ,the same code in C++
//@Author :Ritesh Kumar Gupta
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
vector<vector<int> >GRAPH(100);
inline void print_path(vector<int>path)
{
cout<<"[ ";
for(int i=0;i<path.size();++i)
{
cout<<path[i]<<" ";
}
cout<<"]"<<endl;
}
bool isadjacency_node_not_present_in_current_path(int node,vector<int>path)
{
for(int i=0;i<path.size();++i)
{
if(path[i]==node)
return false;
}
return true;
}
int findpaths(int source ,int target ,int totalnode,int totaledge )
{
vector<int>path;
path.push_back(source);
queue<vector<int> >q;
q.push(path);
while(!q.empty())
{
path=q.front();
q.pop();
int last_nodeof_path=path[path.size()-1];
if(last_nodeof_path==target)
{
cout<<"The Required path is:: ";
print_path(path);
}
else
{
print_path(path);
}
for(int i=0;i<GRAPH[last_nodeof_path].size();++i)
{
if(isadjacency_node_not_present_in_current_path(GRAPH[last_nodeof_path][i],path))
{
vector<int>new_path(path.begin(),path.end());
new_path.push_back(GRAPH[last_nodeof_path][i]);
q.push(new_path);
}
}
}
return 1;
}
int main()
{
//freopen("out.txt","w",stdout);
int T,N,M,u,v,source,target;
scanf("%d",&T);
while(T--)
{
printf("Enter Total Nodes & Total Edges\n");
scanf("%d%d",&N,&M);
for(int i=1;i<=M;++i)
{
scanf("%d%d",&u,&v);
GRAPH[u].push_back(v);
}
printf("(Source, target)\n");
scanf("%d%d",&source,&target);
findpaths(source,target,N,M);
}
//system("pause");
return 0;
}
/*
Input::
1
6 11
1 2
1 3
1 5
2 1
2 3
2 4
3 4
4 3
5 6
5 4
6 3
1 4
output:
[ 1 ]
[ 1 2 ]
[ 1 3 ]
[ 1 5 ]
[ 1 2 3 ]
The Required path is:: [ 1 2 4 ]
The Required path is:: [ 1 3 4 ]
[ 1 5 6 ]
The Required path is:: [ 1 5 4 ]
The Required path is:: [ 1 2 3 4 ]
[ 1 2 4 3 ]
[ 1 5 6 3 ]
[ 1 5 4 3 ]
The Required path is:: [ 1 5 6 3 4 ]
*/
What is working for me is - history.replaceState()
function which is as follows -
history.replaceState(data,"Title of page"[,'url-of-the-page']);
This will not reload page, you can make use of it with event of javascript
I am using SQL Server 2005 Express, and I had to enable Named Pipes connection to be able to backup from the Windows Command. My final script is this:
@echo off
set DB_NAME=Your_DB_Name
set BK_FILE=D:\DB_Backups\%DB_NAME%.bak
set DB_HOSTNAME=Your_DB_Hostname
echo.
echo.
echo Backing up %DB_NAME% to %BK_FILE%...
echo.
echo.
sqlcmd -E -S np:\\%DB_HOSTNAME%\pipe\MSSQL$SQLEXPRESS\sql\query -d master -Q "BACKUP DATABASE [%DB_NAME%] TO DISK = N'%BK_FILE%' WITH INIT , NOUNLOAD , NAME = N'%DB_NAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
echo Done!
echo.
It's working just fine here!!
Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
And on the handler method:
private void WorkerDoWork(int value, string text) {
...
}
I really like this pattern in async/await capable Express/Mongoose apps:
app.delete('/:idToDelete', asyncHandler(async (req, res) => {
const deletedItem = await YourModel
.findByIdAndDelete(req.params.idToDelete) // This method is the nice method for deleting
.catch(err => res.status(400).send(err.message))
res.status(200).send(deletedItem)
}))
To parse complicated types, you start at the variable, go left, and spiral outwards. If there aren't any arrays or functions to worry about (because these sit to the right of the variable name) this becomes a case of reading from right-to-left.
So with char *const a;
you have a
, which is a const
pointer (*
) to a char
. In other words you can change the char which a
is pointing at, but you can't make a
point at anything different.
Conversely with const char* b;
you have b
, which is a pointer (*
) to a char
which is const
. You can make b
point at any char you like, but you cannot change the value of that char using *b = ...;
.
You can also of course have both flavours of const-ness at one time: const char *const c;
.
I happened to try this so I could see the list of files first:
git status | grep "modified:" | awk '{print "git add " $2}' > file.sh
cat ./file.sh
execute:
chmod a+x file.sh
./file.sh
Edit: (see comments) This could be achieved in one step:
git status | grep "modified:" | awk '{print $2}' | xargs git add && git status
this simple solution works for me
final = pd.concat([df, rankingdf], axis=1, sort=False)
but you may need to drop some duplicate column first.
In Mysql, you can not update one table by subquery the same table.
You can separate the query in two parts, or do
UPDATE TABLE_A AS A INNER JOIN TABLE_A AS B ON A.field1 = B.field1 SET field2 = ?
try it-
var radioVal = $("#myform").find("input[type='radio']:checked").val();
console.log(radioVal);
Necroing this question because I recently ran into the problem myself, when trying to add a related property to an existing entity. I just ended up making a nice extension method:
public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, TProperty value)
{
string expressionText = ExpressionHelper.GetExpressionText(expression);
string propertyName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText);
return htmlHelper.Hidden(propertyName, value);
}
Use like so:
@Html.HiddenFor(m => m.RELATED_ID, Related.Id)
Note that this has a similar signature to the built-in HiddenFor, but uses generic typing, so if Value is of type System.Object, you'll actually be invoking the one built into the framework. Not sure why you'd be editing a property of type System.Object in your views though...
Just subscribe to the control's ToolTipTextNeeded event, and return e.TooltipText, much simpler.
perhaps
$id = isset($_GET['id'])?$_GET['id']:null;
and
$other_var = isset($_GET['othervar'])?$_GET['othervar']:null;
I think the easiest way to return a row with the maximum value is by getting its index. argmax()
can be used to return the index of the row with the largest value.
index = df.Value.argmax()
Now the index could be used to get the features for that particular row:
df.iloc[df.Value.argmax(), 0:2]
You could do:
return_it(){
eval ${FUNCNAME[1]}_r_val="\$1"
}
and then use it in your functions like this:
fun1(){
return_it 34
}
fun2(){
fun1; echo $fun1_r_val
}
All the other answers are just focus on the IDE level, these are not the most effective and elegant way to generate getters and setters. If you have tens of attributes, the relevant getters and setters methods will make your class code very verbose.
The best way I ever used to generate getters and setters automatically is using project lombok annotations in your java project, lombok.jar will generate getter and setter method when you compile java code.
You just focus on class attributes/variables naming and definition, lombok will do the rest. This is easy to maintain your code.
For example, if you want to add getter and setter method for age
variable, you just add two lombok annotations:
@Getter @Setter
public int age = 10;
This is equal to code like that:
private int age = 10;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
You can find more details about lombok here: Project Lombok
As an example, I am using a login modal window, where the modal window is the parent, the login form is the child and the login button calls back to the modal parent's close function.
The parent modal contains the function to close the modal. This parent passes the close function to the login child component.
import { Component} from '@angular/core';
import { LoginFormComponent } from './login-form.component'
@Component({
selector: 'my-modal',
template: `<modal #modal>
<login-form (onClose)="onClose($event)" ></login-form>
</modal>`
})
export class ParentModalComponent {
modal: {...};
onClose() {
this.modal.close();
}
}
After the child login component submits the login form, it closes the parent modal using the parent's callback function
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'login-form',
template: `<form (ngSubmit)="onSubmit()" #loginForm="ngForm">
<button type="submit">Submit</button>
</form>`
})
export class ChildLoginComponent {
@Output() onClose = new EventEmitter();
submitted = false;
onSubmit() {
this.onClose.emit();
this.submitted = true;
}
}
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
building on XGreen's approach above, with a few tweaks you can have an animated looping background. See here for example:
$(document).ready(function(){
var images = Array("http://placekitten.com/500/200",
"http://placekitten.com/499/200",
"http://placekitten.com/501/200",
"http://placekitten.com/500/199");
var currimg = 0;
function loadimg(){
$('#background').animate({ opacity: 1 }, 500,function(){
//finished animating, minifade out and fade new back in
$('#background').animate({ opacity: 0.7 }, 100,function(){
currimg++;
if(currimg > images.length-1){
currimg=0;
}
var newimage = images[currimg];
//swap out bg src
$('#background').css("background-image", "url("+newimage+")");
//animate fully back in
$('#background').animate({ opacity: 1 }, 400,function(){
//set timer for next
setTimeout(loadimg,5000);
});
});
});
}
setTimeout(loadimg,5000);
});
echo "Subject: test" | /usr/sbin/sendmail [email protected]
This enables you to do it within one command line without having to echo a text file. This answer builds on top of @mti2935's answer. So credit goes there.
You're talking about template literals.
They allow for both multiline strings and string interpolation.
Multiline strings:
console.log(`foo_x000D_
bar`);_x000D_
// foo_x000D_
// bar
_x000D_
String interpolation:
var foo = 'bar';_x000D_
console.log(`Let's meet at the ${foo}`);_x000D_
// Let's meet at the bar
_x000D_
Associative Arrays in JavaScript don't really work the same as they do in other languages. for each
statements are complicated (because they enumerate inherited prototype properties). You could declare properties on an object/associative array as Pointy mentioned, but really for this sort of thing you should use an array with the push
method:
jsArr = [];
for (var i = 1; i <= 10; i++) {
jsArr.push('example ' + 1);
}
Just don't forget that indexed arrays are zero-based so the first element will be jsArr[0], not jsArr[1].
I believe your syntax is using the Win32_Product Class in WMI. One cause is that this class only displays products installed using Windows Installer (See Here). The Uninstall Registry Key is your best bet.
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
UPDATE FOR COMMENTS:
The Uninstall Registry Key is the standard place to list what is installed and what isn't installed. It is the location that the Add/Remove Programs list will use to populate the list of applications. I'm sure that there are applications that don't list themselves in this location. In that case you'd have to resort to another cruder method such as searching the Program Files directory or looking in the Start Menu Programs List. Both of those ways are definitely not ideal.
In my opinion, looking at the registry key is the best method.
Since this question is from 4 years ago new things have been implemented and among them there is a new function plt.subplots
which is very convenient:
fig, axes = plot.subplots(nrows=2, ncols=3, sharex=True, sharey=True)
where axes
is a numpy.ndarray
of AxesSubplot objects, making it very convenient to go through the different subplots just using array indices [i,j]
.
Take a look at the Huffman algorithm.
https://codereview.stackexchange.com/questions/44473/huffman-code-implementation
The idea is that each character is replaced with sequence of bits, depending on their frequency in the text (the more frequent, the smaller the sequence).
You can read your entire text and build a table of codes, for example:
Symbol Code
a 0
s 10
e 110
m 111
The algorithm builds a symbol tree based on the text input. The more variety of characters you have, the worst the compression will be.
But depending on your text, it could be effective.
How about the following:
unless @players.include?(p.name)
....
end
I believe you need to add the current directory to the Java classpath
java -cp .:./apache-log4j-1.2.16/log4j-1.2.16.jar:./vensim.jar SpatialModel vars
You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?
Try a software called Access to MySQL.
Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.
- Wizard interface.
- Transfer data directly from one server to another.
- Create a dump file.
- Select tables to transfer.
- Select fields to transfer.
- Transfer password protected databases.
- Supports both shared security and user-level security.
- Optional transfer of indexes.
- Optional transfer of records.
- Optional transfer of default values in field definitions.
- Identifies and transfers auto number field types.
- Command line interface.
- Easy install, uninstall and upgrade.
See the aforementioned link for a step-by-step tutorial with screenshots.
Something like:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.
The upcoming Chrome "Scroll to text" feature is exactly what you are looking for....
https://github.com/bokand/ScrollToTextFragment
You basically add #targetText=
at the end of the URL and the browser will scroll to the target text and highlight it after the page is loaded.
It is in the version of Chrome that is running on my desk, but currently it must be manually enabled. Presumably it will soon be enabled by default in the production Chrome builds and other browsers will follow, so OK to start adding to your links now and it will start working then.
Certainly in Eclipse indigo, a yellow line appears under unused imports. If you hover over that, there will be multiple links; one of which will say "Remove unused import". Click that.
If you have multiple unused imports, just hover over one and there will be a link that allows you to remove all unused imports at once. I can't remember the exact wording off hand, but all the links that appear are pretty self explanatory.
You can use the static method Enum.GetNames
which returns an array representing the names of all the items in the enum. The length property of this array equals the number of items defined in the enum
var myEnumMemberCount = Enum.GetNames(typeof(MyEnum)).Length;
00 23 * * * [[ $(date +'%d') -eq $(cal | awk '!/^$/{ print $NF }' | tail -1) ]] && job
Check out a related question on the unix.com forum.
An updated answer here as of 2017, should anyone need it, is that onhashchange
is well supported in all major browsers. See caniuse for details. To use it with jQuery no plugin is needed:
$( window ).on( 'hashchange', function( e ) {
console.log( 'hash changed' );
} );
Occasionally I come across legacy systems where hashbang URL's are still used and this is helpful. If you're building something new and using hash links I highly suggest you consider using the HTML5 pushState API instead.
try boost::asio lib (http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html) it have lot examples.
You could get around this issue using php. You only echo out the code for the popup on first page load.
The other way... Is to set a cookie which is basically a file that sits in your browser and contains some kind of data. On the first page load you would create a cookie. Then every page after that you check if your cookie is set. If it is set do not display the pop up. However if its not set set the cookie and display the popup.
Pseudo code:
if(cookie_is_not_set) {
show_pop_up;
set_cookie;
}
Another way is to change properties "AutoSize" (set to True) and "AutosizeMode" (set to GrowAndShrink).
This has the effect of the form autosizing to the elements on it and never allowing the user to change its size.
To remove you can use this directly:
getSupportFragmentManager().beginTransaction().remove(fragment).
commitAllowingStateLoss();
fragment
is the fragment you want to remove.
For local storage there is a module for that look at below url:
https://github.com/grevory/angular-local-storage
and other link for HTML5 local storage and angularJs
http://www.amitavroy.com/justread/content/articles/html5-local-storage-with-angular-js/
I've created this helper decorator to easily set function attributes:
def with_attrs(**func_attrs):
"""Set attributes in the decorated function, at definition time.
Only accepts keyword arguments.
E.g.:
@with_attrs(counter=0, something='boing')
def count_it():
count_it.counter += 1
print count_it.counter
print count_it.something
# Out:
# >>> 0
# >>> 'boing'
"""
def attr_decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
return fn(*args, **kwargs)
for attr, value in func_attrs.iteritems():
setattr(wrapper, attr, value)
return wrapper
return attr_decorator
A use case is to create a collection of factories and query the data type they can create at a function meta level.
For example (very dumb one):
@with_attrs(datatype=list)
def factory1():
return [1, 2, 3]
@with_attrs(datatype=SomeClass)
def factory2():
return SomeClass()
factories = [factory1, factory2]
def create(datatype):
for f in factories:
if f.datatype == datatype:
return f()
return None
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.
Be sure you fully understand the security issues before using this as a solution.
Easy fix for this might be editing config/mail.php and turning off TLS
'encryption' => env('MAIL_ENCRYPTION', ''), //'tls'),
Basically by doing this
$options['ssl']['verify_peer'] = FALSE;
$options['ssl']['verify_peer_name'] = FALSE;
You should loose security also, but in first option there is no need to dive into Vendor's code.
You can activate the modal without writing any JavaScript simply via data attributes.
The option "show" set to true shows the modal when initialized:
<div class="modal fade" tabindex="-1" role="dialog" data-show="true"></div>
function gitcheckoutall() {
git diff --name-only --diff-filter=U | sed 's/^/"/;s/$/"/' | xargs git checkout --$1
}
I've added this function in .zshrc file.
Use them this way:
gitcheckoutall theirs
or gitcheckoutall ours
Single line:
${str:${#str}-1:1}
Now:
echo "${str:${#str}-1:1}"
password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
submit.performClick();
return true;
}
return false;
}
});
Works very fine for me
In addition hide keyboard
The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input
class(EPL2011_12$Date)
The output should read [1] "Date". If it doesn't, you should format it as a date by inputting
EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")
Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command
EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")
Once you have it in Date format, you can use the subset
command, or you can use brackets
WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]
The window.open method is prone to cause popup blockers to complain
A better approach is:
Put a form in the webpage with an id
<form action="theUrlToGoTo" method="post" target="yourTarget" id="yourFormName">
</form>
Then use:
function openYourRequiredPage() {
var theForm = document.getElementById("yourFormName");
theForm.submit();
}
and
onclick="Javascript: openYourRequiredPage()"
You can use
method="post"
or
method="get"
As you wish
In case anyone else wants to achieve this while using binding. If the id of your view is button_save then this code can be written, taking advantage of the kotlin apply syntax
binding.apply {
button_save.setOnClickListener {
//dosomething
}
}
Take note binding is the name of the binding instance created for an xml file . Full code is below if you are writing the code in fragment. Activity works similarly
private lateinit var binding: FragmentProfileBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentProfileBinding.inflate(inflater, container, false)
return binding.root
}
// onActivityCreated is deprecated in fragment
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.apply {
button_save.setOnClickListener {
//dosomething
}
}
}
The short answer to this question is that none of these values are a reliable indicator of how much memory an executable is actually using, and none of them are really appropriate for debugging a memory leak.
Private Bytes refer to the amount of memory that the process executable has asked for - not necessarily the amount it is actually using. They are "private" because they (usually) exclude memory-mapped files (i.e. shared DLLs). But - here's the catch - they don't necessarily exclude memory allocated by those files. There is no way to tell whether a change in private bytes was due to the executable itself, or due to a linked library. Private bytes are also not exclusively physical memory; they can be paged to disk or in the standby page list (i.e. no longer in use, but not paged yet either).
Working Set refers to the total physical memory (RAM) used by the process. However, unlike private bytes, this also includes memory-mapped files and various other resources, so it's an even less accurate measurement than the private bytes. This is the same value that gets reported in Task Manager's "Mem Usage" and has been the source of endless amounts of confusion in recent years. Memory in the Working Set is "physical" in the sense that it can be addressed without a page fault; however, the standby page list is also still physically in memory but not reported in the Working Set, and this is why you might see the "Mem Usage" suddenly drop when you minimize an application.
Virtual Bytes are the total virtual address space occupied by the entire process. This is like the working set, in the sense that it includes memory-mapped files (shared DLLs), but it also includes data in the standby list and data that has already been paged out and is sitting in a pagefile on disk somewhere. The total virtual bytes used by every process on a system under heavy load will add up to significantly more memory than the machine actually has.
So the relationships are:
There's another problem here; just as shared libraries can allocate memory inside your application module, leading to potential false positives reported in your app's Private Bytes, your application may also end up allocating memory inside the shared modules, leading to false negatives. That means it's actually possible for your application to have a memory leak that never manifests itself in the Private Bytes at all. Unlikely, but possible.
Private Bytes are a reasonable approximation of the amount of memory your executable is using and can be used to help narrow down a list of potential candidates for a memory leak; if you see the number growing and growing constantly and endlessly, you would want to check that process for a leak. This cannot, however, prove that there is or is not a leak.
One of the most effective tools for detecting/correcting memory leaks in Windows is actually Visual Studio (link goes to page on using VS for memory leaks, not the product page). Rational Purify is another possibility. Microsoft also has a more general best practices document on this subject. There are more tools listed in this previous question.
I hope this clears a few things up! Tracking down memory leaks is one of the most difficult things to do in debugging. Good luck.
delete the assemeblyinfo.cs file from project under properties menu and rebulid it.
If you look at the Android resources, the seek bar actually use images.
You have to make a drawable which is transparent on top and bottom for say 10px and the center 5px line is visible.
Refer attached image. You need to convert it into a NinePatch.
We have lot of answers to this question. This answer may be helpful in some scenarios If you want to ignore the null values you can use the NOT_NULL in class level. as below
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}
Some times you may need to ignore the empty values such as you may have initialized the arrayList but there is no elements in that list.In that time using NOT_EMPTY annotation to ignore those empty value fields
@JsonInclude(Include.NON_EMPTY)
class Foo
{
String bar;
}
Remember, 2D array
is not a 2D array
in real sense.Every element of an array in itself is an array, not necessarily of the same size.
so, nir[0].length
may or may not be equal to nir[1].length
or nir[2]length
.
Hope that helps..:)
Answered this just to emphasize @rblarsen comment on question :
You don't need the style tags in the CSS-file
If you remove the style tag from your css file it will work.
I made this simple Notification wrapper. It works on Chrome, Safari and Firefox.
Probably on Opera, IE and Edge as well but I haven't tested it yet.
Just get the notify.js file from here https://github.com/gravmatt/js-notify and put it into your page.
Get it on Bower
$ bower install js-notify
This is how it works:
notify('title', {
body: 'Notification Text',
icon: 'path/to/image.png',
onclick: function(e) {}, // e -> Notification object
onclose: function(e) {},
ondenied: function(e) {}
});
You have to set the title but the json object as the second argument is optional.
This worked for me and it might be useful to another one.
Maybe all components required are not present or/and not all are registered correctly. In order to solve this, try to uncheck all options inside Control Panel -> Turn Windows features on or off -> Internet Information Services -> World Wide Web Services -> Application Development Features, uncheck all options and recheck all then reset the IIS and check if the problem is solved.
Since I can't find a complete or clear answer on this issue, and since it's the second time that I use this post to fix my problems, I post my solution:
why 720? 720 is the error code for connection attempt fail, because your computer and the remote computer could not agree on PPP control protocol, I don't know exactly why it happens, but I think that is all about registry permission for installers and multiple miniport driver install made by vpn installers that are not properly programmed for win 8.1.
Solution:
check write permissions on registers
a. download a Process Monitor http://technet.microsoft.com/en-us//sysinternals/bb896645.aspx and run it
b. Use registry as target and set the filters to check witch registers aren't writable for netsh: "Process Name is 'netsh.exe'" and "result is 'ACCESS DENIED'", then get a command prompt with admin permissions and type netsh int ipv4 reset reset.log
c. for each registry key logged by the process monitor as not accessible, go to registers using regedit anche change these permissions to "complete access"
d. run the following command netsh int ipv6 reset reset.log
and repeat step c)
unistall all not-working miniports
a. go to device managers (windows+x -> device manager)
b. for each not-working miniport (the ones with yellow mark): update driver -> show non-compatible driver -> select another driver (eg. generic broadband adapter)
c. unistall these not working devices
d. reboot your computer
e. Repeat steps a) - d) until you will not see any yellow mark on miniports
delete your vpn connection and create a new one.
that worked for me (2 times, one after my first vpn connection on win 8.1, then when I reinstalled a cisco client and tried to use windows vpn again)
references:
GNU parallel
and xargs
These two tools that can make scripts simpler, and also control the maximum number of threads (thread pool). E.g.:
seq 10 | xargs -P4 -I'{}' echo '{}'
or:
seq 10 | parallel -j4 echo '{}'
See also: how to write a process-pool bash shell
When you annotate a parameter with @RequestHeader
, the parameter retrieves the header information. So you can just do something like this:
@RequestHeader("Accept")
to get the Accept
header.
So from the documentation:
@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
}
The Accept-Encoding
and Keep-Alive
header values are provided in the encoding
and keepAlive
parameters respectively.
And no worries. We are all noobs with something.
t(sapply(a, '[', 1:max(sapply(a, length))))
where 'a' is a list. Would work for unequal row size
You can use StreamReader.ReadToEnd()
,
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
Just press windows button and type %APPDATA% and type enter.
Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.
Please put this code in head section
<link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>
and use font-family: 'Lato', sans-serif;
in your css. For example:
h1 {
font-family: 'Lato', sans-serif;
font-weight: 400;
}
Or you can use manually also
Generate .ttf
font from fontSquiral
and can try this option
@font-face {
font-family: "Lato";
src: url('698242188-Lato-Bla.eot');
src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
url('698242188-Lato-Bla.woff') format('woff'),
url('698242188-Lato-Bla.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
Called like this
body {
font-family: 'Lato', sans-serif;
}
As the previous answer did show an example of how the full hook might look like here is the code of my working post-receive hook:
#!/usr/bin/python
import sys
from subprocess import call
if __name__ == '__main__':
for line in sys.stdin.xreadlines():
old, new, ref = line.strip().split(' ')
if ref == 'refs/heads/master':
print "=============================================="
print "Pushing to master. Triggering jenkins. "
print "=============================================="
sys.stdout.flush()
call(["curl", "-sS", "http://jenkinsserver/git/notifyCommit?url=ssh://user@gitserver/var/git/repo.git"])
In this case I trigger jenkins jobs only when pushing to master and not other branches.
This is what I do to reload the activity after changing returning from a preference change.
@Override
protected void onResume() {
super.onResume();
this.onCreate(null);
}
This essentially causes the activity to redraw itself.
Updated: A better way to do this is to call the recreate()
method. This will cause the activity to be recreated.
Are dictionaries ordered in Python 3.6+?
They are insertion ordered[1]. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. This is considered an implementation detail in Python 3.6; you need to use OrderedDict
if you want insertion ordering that's guaranteed across other implementations of Python (and other ordered behavior[1]).
As of Python 3.7, this is no longer an implementation detail and instead becomes a language feature. From a python-dev message by GvR:
Make it so. "Dict keeps insertion order" is the ruling. Thanks!
This simply means that you can depend on it. Other implementations of Python must also offer an insertion ordered dictionary if they wish to be a conforming implementation of Python 3.7.
How does the Python
3.6
dictionary implementation perform better[2] than the older one while preserving element order?
Essentially, by keeping two arrays.
The first array, dk_entries
, holds the entries (of type PyDictKeyEntry
) for the dictionary in the order that they were inserted. Preserving order is achieved by this being an append only array where new items are always inserted at the end (insertion order).
The second, dk_indices
, holds the indices for the dk_entries
array (that is, values that indicate the position of the corresponding entry in dk_entries
). This array acts as the hash table. When a key is hashed it leads to one of the indices stored in dk_indices
and the corresponding entry is fetched by indexing dk_entries
. Since only indices are kept, the type of this array depends on the overall size of the dictionary (ranging from type int8_t
(1
byte) to int32_t
/int64_t
(4
/8
bytes) on 32
/64
bit builds)
In the previous implementation, a sparse array of type PyDictKeyEntry
and size dk_size
had to be allocated; unfortunately, it also resulted in a lot of empty space since that array was not allowed to be more than 2/3 * dk_size
full for performance reasons. (and the empty space still had PyDictKeyEntry
size!).
This is not the case now since only the required entries are stored (those that have been inserted) and a sparse array of type intX_t
(X
depending on dict size) 2/3 * dk_size
s full is kept. The empty space changed from type PyDictKeyEntry
to intX_t
.
So, obviously, creating a sparse array of type PyDictKeyEntry
is much more memory demanding than a sparse array for storing int
s.
You can see the full conversation on Python-Dev regarding this feature if interested, it is a good read.
In the original proposal made by Raymond Hettinger, a visualization of the data structures used can be seen which captures the gist of the idea.
For example, the dictionary:
d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}
is currently stored as [keyhash, key, value]:
entries = [['--', '--', '--'], [-8522787127447073495, 'barry', 'green'], ['--', '--', '--'], ['--', '--', '--'], ['--', '--', '--'], [-9092791511155847987, 'timmy', 'red'], ['--', '--', '--'], [-6480567542315338377, 'guido', 'blue']]
Instead, the data should be organized as follows:
indices = [None, 1, None, None, None, 0, None, 2] entries = [[-9092791511155847987, 'timmy', 'red'], [-8522787127447073495, 'barry', 'green'], [-6480567542315338377, 'guido', 'blue']]
As you can visually now see, in the original proposal, a lot of space is essentially empty to reduce collisions and make look-ups faster. With the new approach, you reduce the memory required by moving the sparseness where it's really required, in the indices.
[1]: I say "insertion ordered" and not "ordered" since, with the existence of OrderedDict, "ordered" suggests further behavior that the dict
object doesn't provide. OrderedDicts are reversible, provide order sensitive methods and, mainly, provide an order-sensive equality tests (==
, !=
). dict
s currently don't offer any of those behaviors/methods.
[2]: The new dictionary implementations performs better memory wise by being designed more compactly; that's the main benefit here. Speed wise, the difference isn't so drastic, there's places where the new dict might introduce slight regressions (key-lookups, for example) while in others (iteration and resizing come to mind) a performance boost should be present.
Overall, the performance of the dictionary, especially in real-life situations, improves due to the compactness introduced.
In PHP, strings are bytestreams. What exactly are you trying to do?
Re: edit
Ps. Why do I need this at all!? Well I need to send via fputs() bytearray to server written in java...
fputs
takes a string as argument. Most likely, you just need to pass your string to it. On the Java side of things, you should decode the data in whatever encoding, you're using in php (the default is iso-8859-1).
I have a function which returns a CLOB and I was seeing the above error when I'd forgotten to declare the return value as an output parameter. Initially I had:
protected SimpleJdbcCall buildJdbcCall(JdbcTemplate jdbcTemplate)
{
SimpleJdbcCall call = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(catalog)
.withFunctionName(functionName)
.withReturnValue()
.declareParameters(buildSqlParameters());
return call;
}
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
};
}
The buildSqlParameters method should have included the SqlOutParameter:
public SqlParameter[] buildSqlParameters() {
return new SqlParameter[]{
new SqlParameter("p_names", Types.VARCHAR),
new SqlParameter("p_format", Types.VARCHAR),
new SqlParameter("p_units", Types.VARCHAR),
new SqlParameter("p_datums", Types.VARCHAR),
new SqlParameter("p_start", Types.VARCHAR),
new SqlParameter("p_end", Types.VARCHAR),
new SqlParameter("p_timezone", Types.VARCHAR),
new SqlParameter("p_office_id", Types.VARCHAR),
new SqlOutParameter("l_clob", Types.CLOB) // <-- This was missing!
};
}
The premise of the question is flawed, because catching Exception
does catch RuntimeException
. Demo code:
public class Test {
public static void main(String[] args) {
try {
throw new RuntimeException("Bang");
} catch (Exception e) {
System.out.println("I caught: " + e);
}
}
}
Output:
I caught: java.lang.RuntimeException: Bang
Your loop will have problems if:
callbacks
is nullcallbacks
while the loop is executing (if it were a collection rather than an array)Perhaps that's what you're seeing?
See this example :
<?php
echo "<div id='div1'>text</div>"
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#div1').click(function () {
alert('I clicked');
});
});
</script>
</head>
<body>
</body>
</html>
You can use above function for casting not similar class objects (PHP >= 5.3)
/**
* Class casting
*
* @param string|object $destination
* @param object $sourceObject
* @return object
*/
function cast($destination, $sourceObject)
{
if (is_string($destination)) {
$destination = new $destination();
}
$sourceReflection = new ReflectionObject($sourceObject);
$destinationReflection = new ReflectionObject($destination);
$sourceProperties = $sourceReflection->getProperties();
foreach ($sourceProperties as $sourceProperty) {
$sourceProperty->setAccessible(true);
$name = $sourceProperty->getName();
$value = $sourceProperty->getValue($sourceObject);
if ($destinationReflection->hasProperty($name)) {
$propDest = $destinationReflection->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($destination,$value);
} else {
$destination->$name = $value;
}
}
return $destination;
}
EXAMPLE:
class A
{
private $_x;
}
class B
{
public $_x;
}
$a = new A();
$b = new B();
$x = cast('A',$b);
$x = cast('B',$a);
The combination of Ctrl + Shift + Alt + Down worked for me on Linux.
JPanel jPanel = new JPanel();
jPanel.setBorder(BorderFactory.createLineBorder(Color.black));
Here not only jPanel, you can add border to any Jcomponent
Chris Chilvers' advice should be the first course of action but sometimes we're dealing with third party libraries that makes this challenging and requires us to do naughty things... which this is. IMO it's a crime of presumption similar to using !important in CSS.
Having said that, building on Anurag's answer, here are a few additions. These methods allow for multiple events (e.g. "keydown keyup paste"), arbitrary positioning of the handler and reordering after the fact.
$.fn.bindFirst = function (name, fn) {
this.bindNth(name, fn, 0);
}
$.fn.bindNth(name, fn, index) {
// Bind event normally.
this.bind(name, fn);
// Move to nth position.
this.changeEventOrder(name, index);
};
$.fn.changeEventOrder = function (names, newIndex) {
var that = this;
// Allow for multiple events.
$.each(names.split(' '), function (idx, name) {
that.each(function () {
var handlers = $._data(this, 'events')[name.split('.')[0]];
// Validate requested position.
newIndex = Math.min(newIndex, handlers.length - 1);
handlers.splice(newIndex, 0, handlers.pop());
});
});
};
One could extrapolate on this with methods that would place a given handler before or after some other given handler.
To deal with situations where there are a possibility of multiple values (v in your example), I use PIVOT
and LISTAGG
:
SELECT * FROM
(
SELECT id, k, v
FROM _kv
)
PIVOT
(
LISTAGG(v ,',')
WITHIN GROUP (ORDER BY k)
FOR k IN ('name', 'age','gender','status')
)
ORDER BY id;
Since you want dynamic values, use dynamic SQL and pass in the values determined by running a select on the table data before calling the pivot statement.
The problem is, that openssl -verify
does not do the job.
As Priyadi mentioned, openssl -verify
stops at the first self signed certificate, hence you do not really verify the chain, as often the intermediate cert is self-signed.
I assume that you want to be 101% sure, that the certificate files are correct before you try to install them in the productive web service. This recipe here performs exactly this pre-flight-check.
Please note that the answer of Peter is correct, however the output of openssl -verify
is no clue that everything really works afterwards. Yes, it might find some problems, but quite not all.
Here is a script which does the job to verify a certificate chain before you install it into Apache. Perhaps this can be enhanced with some of the more mystic OpenSSL magic, but I am no OpenSSL guru and following works:
#!/bin/bash
# This Works is placed under the terms of the Copyright Less License,
# see file COPYRIGHT.CLL. USE AT OWN RISK, ABSOLUTELY NO WARRANTY.
#
# COPYRIGHT.CLL can be found at http://permalink.de/tino/cll
# (CLL is CC0 as long as not covered by any Copyright)
OOPS() { echo "OOPS: $*" >&2; exit 23; }
PID=
kick() { [ -n "$PID" ] && kill "$PID" && sleep .2; PID=; }
trap 'kick' 0
serve()
{
kick
PID=
openssl s_server -key "$KEY" -cert "$CRT" "$@" -www &
PID=$!
sleep .5 # give it time to startup
}
check()
{
while read -r line
do
case "$line" in
'Verify return code: 0 (ok)') return 0;;
'Verify return code: '*) return 1;;
# *) echo "::: $line :::";;
esac
done < <(echo | openssl s_client -verify 8 -CApath /etc/ssl/certs/)
OOPS "Something failed, verification output not found!"
return 2
}
ARG="${1%.}"
KEY="$ARG.key"
CRT="$ARG.crt"
BND="$ARG.bundle"
for a in "$KEY" "$CRT" "$BND"
do
[ -s "$a" ] || OOPS "missing $a"
done
serve
check && echo "!!! =========> CA-Bundle is not needed! <========"
echo
serve -CAfile "$BND"
check
ret=$?
kick
echo
case $ret in
0) echo "EVERYTHING OK"
echo "SSLCertificateKeyFile $KEY"
echo "SSLCertificateFile $CRT"
echo "SSLCACertificateFile $BND"
;;
*) echo "!!! =========> something is wrong, verification failed! <======== ($ret)";;
esac
exit $ret
Note that the output after
EVERYTHING OK
is the Apache setting, because people usingNginX
orhaproxy
usually can read and understand this perfectly, too ;)
There is a GitHub Gist of this which might have some updates
Prerequisites of this script:
/etc/ssl/certs
as usual for example on UbuntuDIR
where you store 3 files:
DIR/certificate.crt
which contains the certificateDIR/certificate.key
which contains the secret key for your webservice (without passphrase)DIR/certificate.bundle
which contains the CA-Bundle. On how to prepare the bundle, see below../check DIR/certificate
(this assumes that the script is named check
in the current directory)CA-Bundle is not needed
. This means, that you (read: /etc/ssl/certs/
) already trusts the signing certificate. But this is highly unlikely in the WWW.How to create the certificate.bundle
file?
In the WWW the trust chain usually looks like this:
/etc/ssl/certs
certificate.crt
)Now, the evaluation takes place from bottom to top, this means, first, your certificate is read, then the unknown intermediate certificate is needed, then perhaps the cross-signing-certificate and then /etc/ssl/certs
is consulted to find the proper trusted certificate.
The ca-bundle must be made up in excactly the right processing order, this means, the first needed certificate (the intermediate certificate which signs your certificate) comes first in the bundle. Then the cross-signing-cert is needed.
Usually your CA (the authority who signed your certificate) will provide such a proper ca-bundle-file already. If not, you need to pick all the needed intermediate certificates and cat
them together into a single file (on Unix). On Windows you can just open a text editor (like notepad.exe
) and paste the certificates into the file, the first needed on top and following the others.
There is another thing. The files need to be in PEM format. Some CAs issue DER (a binary) format. PEM is easy to spot: It is ASCII readable. For mor on how to convert something into PEM, see How to convert .crt to .pem and follow the yellow brick road.
Example:
You have:
intermediate2.crt
the intermediate cert which signed your certificate.crt
intermediate1.crt
another intermediate cert, which singed intermediate2.crt
crossigned.crt
which is a cross signing certificate from another CA, which signed intermediate1.crt
crossintermediate.crt
which is another intermediate from the other CA which signed crossigned.crt
(you probably will never ever see such a thing)Then the proper cat
would look like this:
cat intermediate2.crt intermediate1.crt crossigned.crt crossintermediate.crt > certificate.bundle
And how can you find out which files are needed or not and in which sequence?
Well, experiment, until the check
tells you everything is OK. It is like a computer puzzle game to solve the riddle. Every. Single. Time. Even for pros. But you will get better each time you need to do this. So you are definitively not alone with all that pain. It's SSL, ya' know? SSL is probably one of the worst designs I ever saw in over 30 years of professional system administration. Ever wondered why crypto has not become mainstream in the last 30 years? That's why. 'nuff said.
Only tested in Chrome 44.
Example: http://codepen.io/hugovk/pen/OVqBoq
HTML:
<div>
<img src="http://lorempixel.com/1600/900/">
</div>
CSS:
<style type="text/css">
img {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
max-width: 100%;
max-height: 100%;
}
</style>
You can select just the part of the string you want to check:
if [ "${HOST:0:4}" = user ]
For your follow-up question, you could use an OR:
if [[ "$HOST" == user1 || "$HOST" == node* ]]
I tested a simple solution that works for me! My javascript was in a js separate file. What I did is that I placed the javascript for the new element into the html that was loaded with ajax, and it works fine for me! This is for those having big files of javascript!!
Follow that tutorial: Disable JavaScript With Chrome DevTools
Summary:
There are several problems here:
The newdata
argument of predict()
needs a predictor variable. You should thus pass it values for Coupon
, instead of Total
, which is the response variable in your model.
The predictor variable needs to be passed in as a named column in a data frame, so that
predict()
knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).
For this to work, your original call should pass df
in through the data
argument, rather than using it directly in your formula. (This way, the name of the column in newdata
will be able to match the name on the RHS of the formula).
With those changes incorporated, this will work:
model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")
To answer your question: no, it's not possible to have multiple versions of IE (if that is what you meant) installed in a 'normal' way (i.e. not a hack, a sandbox or a VM etc). It's perfectly ok to have multiple browsers of different types installed on the same machine, such as IE8, Firefox 3 and Chrome all at once.
SandboxIE should allow you to install multiple versions of IE side-by-side (as well as other software), and this is less hassle than going down the virtual machine route.
However, from a QA point of view I'd strongly recommend installing different versions on different machines as the best option from a testing point of view. This will give you the most realistic testing environment. If you don't have the hardware for that, then virtual machines are the next best option as mentioned in some of the other answers.
Jean-François Corbett's answer is perfect. To be exhaustive I would just like to add that with some restrictons you could also use UsedRange.Columns.Count
or UsedRange.Rows.Count
.
The problem is that UsedRange is not always updated when deleting rows/columns (at least until you reopen the workbook).
I wish comments had proper code text formatting, because I think @1_CR 's answer needs more bumps, and I would like to augment his answer. Anyway, He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are not the same, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this):
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
for line in StringIO.StringIO(variable_with_multiline_string):
pass
print line.strip()
Change HH
to hh
as
long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy hh:mm:ss a");
dateforrow = dateFormat.format(cal1.getTime());
Note that dd/mm/yyyy
- will give you minutes instead of the month.
You can very easily use this to re-use the value of the variable in another function.
// Use this in source window.var1= oEvent.getSource().getBindingContext();
// Get value of var1 in destination var var2= window.var1;
Adding on to the one mentioned by @abarnert
a better one is to catch the exception
import subprocess
try:
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)
#print('py2 said:', py2output)
print "here"
except subprocess.CalledProcessError as e:
print "Calledprocerr"
this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting
python: can't open file 'py2.py': [Errno 2] No such file or directory
Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script
Here are my two cents:
function stringFormat(str) {
if (str !== undefined && str !== null) {
str = String(str);
if (str.trim() !== "") {
var args = arguments;
return str.replace(/(\{[^}]+\})/g, function(match) {
var n = +match.slice(1, -1);
if (n >= 0 && n < args.length - 1) {
var a = args[n + 1];
return (a !== undefined && a !== null) ? String(a) : "";
}
return match;
});
}
}
return "";
}
alert(stringFormat("{1}, {0}. You're looking {2} today.",
"Dave", "Hello", Math.random() > 0.5 ? "well" : "good"));
Math.NET's Iridium library provides a fast, regularly updated collection of math-related functions, including the FFT. It's licensed under the LGPL so you are free to use it in commercial products.
If your goal is to initialize the static variable in your header file (instead of a *.cpp file, which you may want if you are sticking to a "header only" idiom), then you can work around the initialization problem by using a template. Templated static variables can be initialized in a header, without causing multiple symbols to be defined.
See here for an example:
I had this problem where the "clean up" worked, but the "update" would continue to fail. The solution that worked was to delete the folder in question via Windows Explorer, not TortoiseSVN's delete (which marks the deletion as something to commit to the repository, and then I did a "checkout" to essentially "update" the folder from the respository.
More info on the difference between an O/S delete and an SVN delete here: http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-rename.html
Notably:
When you TortoiseSVN ? Delete a file, it is removed from your working copy immediately as well as being marked for deletion in the repository on next commit.
And:
If a file is deleted via the explorer instead of using the TortoiseSVN context menu, the commit dialog shows those files and lets you remove them from version control too before the commit. However, if you update your working copy, Subversion will spot the missing file and replace it with the latest version from the repository.
I've used IP*Works SSH and it is great. Easy to setup and use. Plus, their support is top-notch when you run into questions or problems.
Complete guide : https://developer.android.com/studio/build/application-id.html
As per Android official Blogs : https://android-developers.googleblog.com/2011/06/things-that-cannot-change.html
We can say that:
If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.
If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.
As per Google App Update check list : https://support.google.com/googleplay/android-developer/answer/113476?hl=en
Update your apps
Prepare your APK
When you're ready to make changes to your APK, make sure to update your app’s version code as well so that existing users will receive your update.
Use the following checklist to make sure your new APK is ready to update your existing users:
To verify that your APK is using the same certification as the previous version, you can run the following command on both APKs and compare the results:
$ jarsigner -verify -verbose -certs my_application.apk
If the results are identical, you’re using the same key and are ready to continue. If the results are different, you will need to re-sign the APK with the correct key.
Learn more about signing your applications
Upload your APK Once your APK is ready, you can create a new release.
If by any chance you use VSCode and has installed the docker extension, just right+click on the docker you want to check (within the docker extension), click on Inspect, and there search for env, you will find all your env variables values
Create a POJO Java Class for the objects in the list like so:
class NameUrlClass{
private String name;
private String url;
//Constructor
public NameUrlClass(String name,String url){
this.name = name;
this.url = url;
}
}
Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:
List<NameUrlClass> obj = new ArrayList<NameUrlClass>;
You can use store the JSON array in this object
obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]
You have two records in your json file, and json.loads()
is not able to decode more than one. You need to do it record by record.
See Python json.loads shows ValueError: Extra data
OR you need to reformat your json to contain an array:
{
"foo" : [
{"name": "XYZ", "address": "54.7168,94.0215", "country_of_residence": "PQR", "countries": "LMN;PQRST", "date": "28-AUG-2008", "type": null},
{"name": "OLMS", "address": null, "country_of_residence": null, "countries": "Not identified;No", "date": "23-FEB-2017", "type": null}
]
}
would be acceptable again. But there cannot be several top level objects.
Javascript arrays have a length property. Use it like this:
st.itemb.length
You can make the copy constructor private and provide no implementation:
private:
SymbolIndexer(const SymbolIndexer&);
Or in C++11, explicitly forbid it:
SymbolIndexer(const SymbolIndexer&) = delete;
In this tar.gz file compress in open view directory In solve use os.path.basename(file_directory)
with tarfile.open("save.tar.gz","w:gz"):
for file in ["a.txt","b.log","c.png"]:
tar.add(os.path.basename(file))
its use in tar.gz file compress in directory
Probably, it will not matter at all. Read this post on Coding Horror ;): http://www.codinghorror.com/blog/archives/001218.html
Just change the SqlCommand.CommandText
instead of creating a new SqlCommand
every time. There is no need to close and reopen the connection.
// Create the first command and execute
var command = new SqlCommand("<SQL Command>", myConnection);
var reader = command.ExecuteReader();
// Change the SQL Command and execute
command.CommandText = "<New SQL Command>";
command.ExecuteNonQuery();
When you dont want to put your hand yon regular expression (may be you should) you could first replace all "Milan Vasic" string with "Milan".
And than replace all "Milan" Strings with "Milan Vasic".
$mystring = "this is the text I would like to truncate";
// Pass your variable to the function
$mystring = truncate($mystring);
// Truncated tring printed out;
echo $mystring;
//truncate text function
public function truncate($text) {
//specify number fo characters to shorten by
$chars = 25;
$text = $text." ";
$text = substr($text,0,$chars);
$text = substr($text,0,strrpos($text,' '));
$text = $text."...";
return $text;
}
you can use class "img-fluid" for newer version i.e Bootstrap v4.
and can use class "img-responsive" for older version like Bootstrap v3.
Usage:-
img tag with :-
class="img-fluid"
src="..."
Change the submit button to a normal button and handle submitting in its onClick event.
As far as I know, there is no way to tell if the form was submitted by Enter Key or the submit button.
This is the default working setup https://www.youtube.com/watch?v=XiD7JTCBdpI
Use Connection Method: standard TCP/IP over ssh
Then ssh hostname: 127.0.0.1:2222
SSH Username: vagrant password vagrant
MySQL Hostname: localhost
Username: homestead password:secret
The docs say regarding list-style-position
: outside
CSS1 did not specify the precise location of the marker box and for reasons of compatibility, CSS2 remains equally ambiguous. For more precise control of marker boxes, please use markers.
Further up that page is the stuff about markers.
One example is:
LI:before {
display: marker;
content: "(" counter(counter) ")";
counter-increment: counter;
width: 6em;
text-align: center;
}
Shift+ESC
This hides/closes any of the 'fake window' windows in Visual Studio. This includes things like the Solution Explorer, Object Browser, Output Window, Immediate window, Unit Test Windows etc. etc. and still applies whether they're pinned, floating, dockable or tabbed.
Shortcut into a window (e.g. Ctrl + Alt + L or Ctrl + Alt + I) do what you need to do, and Shift + Esc to get rid of it. If you don't get rid of it, the only way to give it focus again is to use the same keyboard shortcut (or the mouse, which is what we're trying to avoid....)
Once you get the hang of it, it's immensely useful.
Grrr....The amount of times of hit Ctrl + F4 to close the 'window' only to see my current code window close was insane before I found this, now it only happens occasionally..
Are you trying to get visitors to old.com/about.htm to go to new.com/about.htm? If so, you can do this with a mod_rewrite rule in .htaccess:
RewriteEngine on
RewriteRule ^(.*)$ http://www.thenewdomain.com/$1 [R=permanent,L]
if anyone has a problem on Mac, can try this
sudo pip install --upgrade matplotlib --ignore-installed six
Follow this steps:
-Build
-Generate Signed Apk
-Create new
Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)
Adding to this question if you ever have more than one columns to remap in a data dataframe:
def remap(data,dict_labels):
"""
This function take in a dictionnary of labels : dict_labels
and replace the values (previously labelencode) into the string.
ex: dict_labels = {{'col1':{1:'A',2:'B'}}
"""
for field,values in dict_labels.items():
print("I am remapping %s"%field)
data.replace({field:values},inplace=True)
print("DONE")
return data
Hope it can be useful to someone.
Cheers
Here is another example that return's a boolean value using try/catch.
private boolean doSomeThing(int index){
try {
if(index%2==0)
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
System.out.println("Finally!!! ;) ");
}
return false;
}
What about ordering desc by the desired property,
blah = blah.OrderByDescending(x => x.Property);
And then doing something like
if (!descending)
{
blah = blah.Reverse()
}
else
{
// Already sorted desc ;)
}
Is it Reverse() too slow?
In your action you need first to load companies like so :
$companies = App\Company::all();
return view('listing.company')->with('companies' => $companies)->render();
This will make the companies variable available in the view, and it should render the HTML correctly.
Try to use postman chrome extension to debug your view.
You can use lib https://github.com/kssource/BitSequence. It accept a number and return bynary string, padded and/or grouped.
String s = new BitSequence(2, 16).toBynaryString(ALIGN.RIGHT, GROUP.CONTINOUSLY));
return
0000000000000010
another examples:
[10, -20, 30]->00001010 11101100 00011110
i=-10->00000000000000000000000000001010
bi=10->1010
sh=10->00 0000 0000 1010
l=10->00000001 010
by=-10->1010
i=-10->bc->11111111 11111111 11111111 11110110
Here is another solution which uses any/2
map(select(any(.Names[]; contains("data"))|not)|.Id)[]
with the sample data and the -r
option it produces
cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19
DateTime is value type, so it can not never be null. If you think DateTime? ( Nullable ) you can use:
DateTime? something = GetDateTime();
bool isNull = (something == null);
bool isNull2 = !something.HasValue;
I created a more comprehensive and cleaner version that some people might find useful for remembering which name corresponds to which value. I used Chrome Dev Tool's color code and labels are organized symmetrically to pick up analogies faster:
Note 1: clientLeft
also includes the width of the vertical scroll
bar if the direction of the text is set to right-to-left (since the
bar is displayed to the left in that case)
Note 2: the outermost line represents the closest positioned parent
(an element whose position
property is set to a value different than
static
or initial
). Thus, if the direct container isn’t a positioned
element, then the line doesn’t represent the first container in
the hierarchy but another element higher in the hierarchy. If no
positioned parent is found, the browser will take the html
or body
element as reference
Hope somebody finds it useful, just my 2 cents ;)
You can use MSSQL Server Auditing feature. From version SQL Server 2012 you will find this feature in all editions:
Try using step="0.01"
, then it will step by a penny each time.
eg:
<input type="number" min="0.00" max="10000.00" step="0.01" />
_x000D_
or programmaticaly
String s = String.class.getName();
s = s.substring(s.lastIndexOf('.') + 1);
A way for integers without banal converting to string
:
var num = 9999999999; // your number
var length = 1;
while (num >= 10) {
num /= 10;
length++;
}
alert(length);
In my case, it was a missing line break that added unneeded parameters due to a bad copy and paste.
I followed a guide at https://pytorch.org/docs/stable/notes/windows.html#include-optional-components which looks like this when you copy it right here without any editing:
REM Make sure you have 7z and curl installed.
REM Download MKL files
curl https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z -k -O 7z x -aoa mkl_2020.0.166.7z -omkl
Output:
C:\Users\Admin>curl "https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z" -k -O 7z x
-aoa mkl_2020.0.166.7z -omkl
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 103M 100 103M 0 0 5063k 0 0:00:21 0:00:21 --:--:-- 5629k
0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0curl: (6) Could not resolve host: 7z
0 0 0 0 0 0 0 0 --:--:-- 0:00:01 --:--:-- 0curl: (6) Could not resolve host: x
curl: (6) Could not resolve host: mkl_2020.0.166.7z
There is actually a line break before "7z", with "7z" as the executable (and before, in addition to adding curl to your user PATH
, you need to add 7z to the user PATH
as well, for example with setx PATH "%PATH%;C:\Program Files\7-Zip\"
):
REM Download MKL files
curl https://s3.amazonaws.com/ossci-windows/mkl_2020.0.166.7z -k -O
7z x -aoa mkl_2020.0.166.7z -omkl
In my case, changing the IISExpress port number in my project properties, solved the problem.
$name -replace ";*",""
You were close, but you used the syntax of a wildcard expresson rather than a regular expression, which is what the -replace
operator expects.
Therefore (hash sequence shortened):
PS> 'test.txt ; 131 136 80 89 119 17 60 123 210 121 188' -replace '\s*;.*'
test.txt
Note:
Omitting the substitution-text operand (the 2nd RHS operand) implicitly uses ""
(the empty string), i.e. it effectively removes what the regex matched.
.*
is what represents a potentially empty run (*
) of characters (.
) in a regex - it is the regex equivalent of *
by itself in a wildcard expression.
Adding \s*
before the ;
in the regex also removes trailing whitespace (\s
) after the filename.
I've used '...'
rather than "..."
to enclose the regex, so as to prevent confusion between what PowerShell expands up front (see expandable strings in PowerShell and what the .NET regex engine sees.
Use this in your paint properties:
textPaint.setTextAlign(Paint.Align.CENTER);
This worked for me like a charm:
row.DataGridView.Enabled = false;
row.DefaultCellStyle.BackColor = Color.LightGray;
row.DefaultCellStyle.ForeColor = Color.DarkGray;
(where row = DataGridView.NewRow(appropriate overloads);)
The token has to be placed in an Authorization header according to the following format:
Authorization: Bearer [Token_Value]
import urllib2
import json
def get_auth_token():
"""
get an auth token
"""
req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
token_string=json_obj["token"].encode("ascii","ignore")
return token_string
def get_response_json_object(url, auth_token):
"""
returns json object with info
"""
auth_token=get_auth_token()
req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
response=urllib2.urlopen(req)
html=response.read()
json_obj=json.loads(html)
return json_obj
You can link to file, but not to folders, and keep in mind that, Github will add /blob/master/
before your relative link(and folders lacks that part so they cannot be linked, neither with HTML <a>
tags or Markdown link).
So, if we have a file in myrepo/src/Test.java
, it will have a url like:
https://github.com/WesternGun/myrepo/blob/master/src/Test.java
And to link it in the readme file, we can use:
[This is a link](src/Test.java)
or: <a href="src/Test.java">This is a link</a>
.
(I guess, master
represents the master
branch and it differs when the file is in another branch.)
Since "mathematically" both are correct:
-13 % 64 = -13 (on modulus 64)
-13 % 64 = 51 (on modulus 64)
One of the options had to be chosen by Java language developers and they chose:
the sign of the result equals the sign of the dividend.
Says it in Java specs:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3
In my case I console.log(this.$route)
and returned the fullPath:
console.js:
fullPath: "/solicitud/MX/666",
params: {market: "MX", id: "666"},
path: "/solicitud/MX/666"
console.js: /solicitud/MX/666
LR is link register used to hold the return address for a function call.
SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.
From the ARM architecture reference:
SP, the Stack Pointer
Register R13 is used as a pointer to the active stack.
In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.
LR, the Link Register
Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.
When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:
• Return with a BX LR instruction.
• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...
Let's suppose you want to find all int
not preceded by unsigned
:
With support for negative look-behind:
(?<!unsigned )int
Without support for negative look-behind:
((?!unsigned ).{9}|^.{0,8})int
Basically idea is to grab n preceding characters and exclude match with negative look-ahead, but also match the cases where there's no preceeding n characters. (where n is length of look-behind).
So the regex in question:
(?<!filename)\.js$
would translate to:
((?!filename).{8}|^.{0,7})\.js$
You might need to play with capturing groups to find exact spot of the string that interests you or you want't to replace specific part with something else.
Empty lists evaluate to False in boolean contexts (such as if some_list:
).
If you need to work with indices of a sequence, then yes - you use it... eg for the equivalent of numpy.argsort...:
>>> a = [6, 3, 1, 2, 5, 4]
>>> sorted(range(len(a)), key=a.__getitem__)
[2, 3, 1, 5, 4, 0]
I had the same question, but I also wanted the first line (header) to stay on top. So I needed to use the power of awk
cat dax-weekly.csv | awk '1 { last = NR; line[last] = $0; } END { print line[1]; for (i = last; i > 1; i--) { print line[i]; } }'
PS also works in cygwin or gitbash
I try my darned best to write exception-safe code, yes.
That means I take care to keep an eye on which lines can throw. Not everyone can, and it is critically important to keep that in mind. The key is really to think about, and design your code to satisfy, the exception guarantees defined in the standard.
Can this operation be written to provide the strong exception guarantee? Do I have to settle for the basic one? Which lines may throw exceptions, and how can I ensure that if they do, they don't corrupt the object?
Maybe this code helps:
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
Well, I had few deleted branches like dev/{feature_branch} and when I created a new branch dev and tried to checkout, I was getting the same issue. I ran the below command
git fetch -p
and worked for me.
Transactions are intended to run completely or not at all. The only way to complete a transaction is to commit, any other way will result in a rollback.
Therefore, if you begin and then not commit, it will be rolled back on connection close (as the transaction was broken off without marking as complete).
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'
or simply this if you are sure that you have no values like this CKIT002
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
To delete a cookie I set it again with an empty value and expiring in 1 second. In details, I always use one of the following flavours (I tend to prefer the second one):
1.
function setCookie(key, value, expireDays, expireHours, expireMinutes, expireSeconds) {
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = key +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie(name, "", null , null , null, 1);
}
Usage:
setCookie("reminder", "buyCoffee", null, null, 20);
deleteCookie("reminder");
2
function setCookie(params) {
var name = params.name,
value = params.value,
expireDays = params.days,
expireHours = params.hours,
expireMinutes = params.minutes,
expireSeconds = params.seconds;
var expireDate = new Date();
if (expireDays) {
expireDate.setDate(expireDate.getDate() + expireDays);
}
if (expireHours) {
expireDate.setHours(expireDate.getHours() + expireHours);
}
if (expireMinutes) {
expireDate.setMinutes(expireDate.getMinutes() + expireMinutes);
}
if (expireSeconds) {
expireDate.setSeconds(expireDate.getSeconds() + expireSeconds);
}
document.cookie = name +"="+ escape(value) +
";domain="+ window.location.hostname +
";path=/"+
";expires="+expireDate.toUTCString();
}
function deleteCookie(name) {
setCookie({name: name, value: "", seconds: 1});
}
Usage:
setCookie({name: "reminder", value: "buyCoffee", minutes: 20});
deleteCookie("reminder");
In case if you observe a strict host key check error then use -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null
options.
The complete example is as follows
sshpass -p "password" scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null [email protected]:/tmp/from/psoutput /tmp/to/psoutput
You could use the tr
instead:
$p =~ tr/fo//d;
will delete every f and every o from $p
. In your case it should be:
$p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d
tr/SEARCHLIST/REPLACEMENTLIST/cdsr
Transliterates all occurrences of the characters found (or not found if the
/c
modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.[…]
If the
/d
modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
Native JSON support has been included in PHP since 5.2 in the form of methods json_encode()
and json_decode()
. You would use the first to output a PHP variable in JSON.
You forgot to add std::
namespace prefix to vector
class name.
This Can be Done by Style Property.
<!DOCTYPE html>
<html>
<head>
<style>
#main {
display: flex;
}
#main div {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 40px;
}
</style>
</head>
<body>
<div id="main">
<div style="background-color:coral;">Red DIV</div>
<div style="background-color:lightblue;" id="myBlueDiv">Blue DIV</div>
</div>
</body>
</html>
Its Result will be :
Enjoy... Please Note: This works in Higher version of CSS (>3.0).
In my case, I had to comment out com.google.firebase.firebase-crash
plugin:
apply plugin: 'com.android.application'
// apply plugin: 'com.google.firebase.firebase-crash' <== this plugin causes the error
It is a bug since Android Studio 3.3.0
well it's deprecated in android M so you must make exception for android M and lower. Just add current theme on getColor
function. You can get current theme with getTheme()
.
This will do the trick in fragment, you can replace getActivity()
with getBaseContext()
, yourContext
, etc which hold your current context
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white, getActivity().getTheme()));
}else {
yourTitle.setTextColor(getActivity().getResources().getColor(android.R.color.white));
}
*p.s : color is deprecated in M, but drawable is deprecated in L
>## open command prompt with Run as Administrtor ##
adb connect ipdevice:5037
Another option in case you don't wanna use a plugin:
Ctrl+` or
View -> Show Console
type on the console the following command:
view.encoding()
In case you want to something more intrusive, there's a option to create an shortcut that executes the following command:
sublime.message_dialog(view.encoding())
this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
Try this. There shouldn't be any warning...
Activity thisActivity = getActivity();
if (thisActivity != null) {
startActivity(new Intent(thisActivity, yourActivity.class)); // if needed
thisActivity.finish();
}
The read
method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in struct
module: http://docs.python.org/library/struct.html.
import struct
print(struct.unpack('i', fin.read(4)))
Note that unpack
always returns a tuple, so struct.unpack('i', fin.read(4))[0]
gives the integer value that you are after.
You should probably use the format string '<i'
(< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order.
You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html
geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()
You seem to have used some [Authorize]
attribute on your Web API controller action and I don't see how this is relevant to your question.
So, let's get into practice. Here's a how a trivial Web API controller might look like:
public class TestController : ApiController
{
public string Post([FromBody] string value)
{
return value;
}
}
and a consumer for that matter:
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
Console.WriteLine(result);
}
}
}
You will undoubtedly notice the [FromBody]
decoration of the Web API controller attribute as well as the =
prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.
As far as the [Authorize]
attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post
that I wrote on this topic interesting to get you started.
And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.
Same with something more complex...getting the ec2 instance region from within the instance.
INSTANCE_REGION=$(curl -s 'http://169.254.169.254/latest/dynamic/instance-identity/document' | python -c "import sys, json; print json.load(sys.stdin)['region']")
echo $INSTANCE_REGION
I've used this method successfully:
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)
You'll need to cast the returned object to your desired object type.
You can simplify the code by introducing an extra variable.
#include <string.h>
#include <stdio.h>
int main()
{
char str[100], *s = str, *t = NULL;
strcpy(str, "a space delimited string");
while ((t = strtok(s, " ")) != NULL) {
s = NULL;
printf(":%s:\n", t);
}
return 0;
}
If the date and time is in its own cell (aka textbox), then you should look at applying the format to the entire textbox. This will create cleaner exports to other formats; in particular, the value will export as a datetime value to Excel instead of a string.
Use the properties pane or dialog to set the format for the textbox to "MM/dd/yyyy hh:mm tt"
I would only use Ian's answer if the datetime is being concatenated with another string.
And here comes the PHP implementation of the ZSCORE algo:
<?php
$y = array(1,7,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,10,3,2,5,3,2,1,1,1,0.9,1,1,3,
2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1);
function mean($data, $start, $len) {
$avg = 0;
for ($i = $start; $i < $start+ $len; $i ++)
$avg += $data[$i];
return $avg / $len;
}
function stddev($data, $start,$len) {
$mean = mean($data,$start,$len);
$dev = 0;
for ($i = $start; $i < $start+$len; $i++)
$dev += (($data[$i] - $mean) * ($data[$i] - $mean));
return sqrt($dev / $len);
}
function zscore($data, $len, $lag= 20, $threshold = 1, $influence = 1) {
$signals = array();
$avgFilter = array();
$stdFilter = array();
$filteredY = array();
$avgFilter[$lag - 1] = mean($data, 0, $lag);
$stdFilter[$lag - 1] = stddev($data, 0, $lag);
for ($i = 0; $i < $len; $i++) {
$filteredY[$i] = $data[$i];
$signals[$i] = 0;
}
for ($i=$lag; $i < $len; $i++) {
if (abs($data[$i] - $avgFilter[$i-1]) > $threshold * $stdFilter[$lag - 1]) {
if ($data[$i] > $avgFilter[$i-1]) {
$signals[$i] = 1;
}
else {
$signals[$i] = -1;
}
$filteredY[$i] = $influence * $data[$i] + (1 - $influence) * $filteredY[$i-1];
}
else {
$signals[$i] = 0;
$filteredY[$i] = $data[$i];
}
$avgFilter[$i] = mean($filteredY, $i - $lag, $lag);
$stdFilter[$i] = stddev($filteredY, $i - $lag, $lag);
}
return $signals;
}
$sig = zscore($y, count($y));
print_r($y); echo "<br><br>";
print_r($sig); echo "<br><br>";
for ($i = 0; $i < count($y); $i++) echo $i. " " . $y[$i]. " ". $sig[$i]."<br>";
Please use Like below.
<a style="cursor: pointer" **(click)="yourFunctionComponent()"** >
<i class="fa fa-dribbble fa-4x"></i>
</a>
The above can be used so that the fa icon will be shown and also on the click function you could write your logic.
If you have a return value you need to send to the UI you can use the generic version like this:
This is being called from an MVVM ViewModel in my case.
var updateManifest = Task<ShippingManifest>.Run(() =>
{
Thread.Sleep(5000); // prove it's really working!
// GenerateManifest calls service and returns 'ShippingManifest' object
return GenerateManifest();
})
.ContinueWith(manifest =>
{
// MVVM property
this.ShippingManifest = manifest.Result;
// or if you are not using MVVM...
// txtShippingManifest.Text = manifest.Result.ToString();
System.Diagnostics.Debug.WriteLine("UI manifest updated - " + DateTime.Now);
}, TaskScheduler.FromCurrentSynchronizationContext());
You need make your Contact classes implement Comparable, and then implement the compareTo(Contact)
method. That way, the Collections.sort will be able to sort them for you. Per the page I linked to, compareTo 'returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.'
For example, if you wanted to sort by name (A to Z), your class would look like this:
public class Contact implements Comparable<Contact> {
private String name;
// all the other attributes and methods
public compareTo(Contact other) {
return this.name.compareTo(other.name);
}
}
$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');
Case in method names is important, so no addclass
.
$('#my_select option:selected').attr('id');
Found this:
If
items()
,keys()
,values()
,iteritems()
,iterkeys()
, anditervalues()
are called with no intervening modifications to the dictionary, the lists will directly correspond.
On 2.x documentation and 3.x documentation.