Does Java have an exponential operator?
There is no operator, but there is a method.
Math.pow(2, 3) // 8.0
Math.pow(3, 2) // 9.0
FYI, a common mistake is to assume 2 ^ 3
is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.
Is there an exponent operator in C#?
The lack of an exponential operator for C# was a big annoyance for us when looking for a new language to convert our calculation software to from the good ol' vb6.
I'm glad we went with C# but it still annoys me whenever I'm writing a complex equation including exponents. The Math.Pow()
method makes equations quite hard to read IMO.
Our solution was to create a special DoubleX
class where we override the ^
-operator (see below)
This works fairly well as long as you declare at least one of the variables as DoubleX
:
DoubleX a = 2;
DoubleX b = 3;
Console.WriteLine($"a = {a}, b = {b}, a^b = {a ^ b}");
or use an explicit converter on standard doubles:
double c = 2;
double d = 3;
Console.WriteLine($"c = {c}, d = {d}, c^d = {c ^ (DoubleX)d}"); // Need explicit converter
One problem with this method though is that the exponent is calculated in the wrong order compared to other operators. This can be avoided by always putting an extra (
)
around the operation which again makes it a bit harder to read the equations:
DoubleX a = 2;
DoubleX b = 3;
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + a ^ b}"); // Wrong result
Console.WriteLine($"a = {a}, b = {b}, 3+a^b = {3 + (a ^ b)}"); // Correct result
I hope this can be of help to others who uses a lot of complex equations in their code, and maybe someone even has an idea of how to improve this method?!
DoubleX
class:
using System;
namespace ExponentialOperator
{
/// <summary>
/// Double class that uses ^ as exponential operator
/// </summary>
public class DoubleX
{
#region ---------------- Fields ----------------
private readonly double _value;
#endregion ------------- Fields ----------------
#region -------------- Properties --------------
public double Value
{
get { return _value; }
}
#endregion ----------- Properties --------------
#region ------------- Constructors -------------
public DoubleX(double value)
{
_value = value;
}
public DoubleX(int value)
{
_value = Convert.ToDouble(value);
}
#endregion ---------- Constructors -------------
#region --------------- Methods ----------------
public override string ToString()
{
return _value.ToString();
}
#endregion ------------ Methods ----------------
#region -------------- Operators ---------------
// Change the ^ operator to be used for exponents.
public static DoubleX operator ^(DoubleX value, DoubleX exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(DoubleX value, double exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(double value, DoubleX exponent)
{
return Math.Pow(value, exponent);
}
public static DoubleX operator ^(DoubleX value, int exponent)
{
return Math.Pow(value, exponent);
}
#endregion ----------- Operators ---------------
#region -------------- Converters --------------
// Allow implicit convertion
public static implicit operator DoubleX(double value)
{
return new DoubleX(value);
}
public static implicit operator DoubleX(int value)
{
return new DoubleX(value);
}
public static implicit operator Double(DoubleX value)
{
return value._value;
}
#endregion ----------- Converters --------------
}
}
data.frame Group By column
require(reshape2)
T <- melt(df, id = c("A"))
T <- dcast(T, A ~ variable, sum)
I am not certain the exact advantages over aggregate.
Google Geocoding API - REQUEST_DENIED
I got this problem as well using the drupal 7 Location module. Autofilling all empty locations resulted in this error. Executing one of the requests to the location api manually resulted in this error in the returned JSON:
"Browser API keys cannot have referer restrictions when used with this API."
Resolving the problem then was easy: create a new key without any restrictions and use it only for Geocoding.
Note for those new to google api keys: by restrictions they mean limiting requests using an api key to specific domains / subdomains. (eg. only request from http://yourdomain.com are allowed).
Disable Copy or Paste action for text box?
Best way to do this is to add a data attribute to the field (textbox) where you want to avoid the cut,copy and paste.
Just create a method for the same which is as follows :-
function ignorePaste() {
$("[data-ignorepaste]").bind("cut copy paste", function (e) {
e.preventDefault(); //prevent the default behaviour
});
};
Then once when you add the above code simply add the data attribute to the field where you want to ignore cut copy paste. in our case your add a data attribute to confirm email text box as below :-
Confirm Email: <input type="textbox" id= "confirmEmail" data-ignorepaste=""/>
Call the method ignorePaste()
So in this way you will be able to use this throughout the application, all you need to do is just add the data attribute where you want to ignore cut copy paste
https://jsfiddle.net/0ac6pkbf/21/
Unsigned keyword in C++
Does the unsigned keyword default to a data type in C++
Yes,signed and unsigned may also be used as standalone type specifiers
The integer data types char, short, long and int can be either signed or unsigned depending on the range of numbers needed to be represented. Signed types can represent both positive and negative values, whereas unsigned types can only represent positive values (and zero).
An unsigned integer containing n bits can have a value between 0 and 2n - 1
(which is 2n different values).
However,signed and unsigned may also be used as standalone type specifiers, meaning the same as signed int and unsigned int respectively. The following two declarations are equivalent:
unsigned NextYear;
unsigned int NextYear;
How to undo 'git reset'?
My situation was slightly different, I did git reset HEAD~
three times.
To undo it I had to do
git reset HEAD@{3}
so you should be able to do
git reset HEAD@{N}
But if you have done git reset using
git reset HEAD~3
you will need to do
git reset HEAD@{1}
{N} represents the number of operations in reflog, as Mark pointed out in the comments.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
When to use window.opener / window.parent / window.top
I think you need to add some context to your question. However, basic information about these things can be found here:
window.opener
https://developer.mozilla.org/en-US/docs/Web/API/Window.opener
I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.
window.parent
https://developer.mozilla.org/en-US/docs/Web/API/Window.parent
I've used this mostly when working with IFrames that need to communicate with the window object that contains them.
window.top
https://developer.mozilla.org/en-US/docs/Web/API/Window.top
This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.
If you add some more detail to your question, I can supply other more relevant examples.
UPDATE:
There are a few ways you can handle your situation.
You have the following structure:
- Main Window
- Dialog 1
- Dialog 2 Opened By Dialog 1
When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.
So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:
childwindow.appMainWindow = window.opener
After making the assignment above, close dialog 1.
Then from the code running inside dialog2, you should be able to use
window.appMainWindow
to reference the main window, window object.
Hope this helps.
How to store NULL values in datetime fields in MySQL?
MySQL does allow NULL
values for datetime
fields. I just tested it:
mysql> create table datetimetest (testcolumn datetime null default null);
Query OK, 0 rows affected (0.10 sec)
mysql> insert into datetimetest (testcolumn) values (null);
Query OK, 1 row affected (0.00 sec)
mysql> select * from datetimetest;
+------------+
| testcolumn |
+------------+
| NULL |
+------------+
1 row in set (0.00 sec)
I'm using this version:
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.0.45 |
+-----------+
1 row in set (0.03 sec)
EDIT #1: I see in your edit that the error message you are getting in PHP indicates that you are passing an empty string (i.e. ''
), not null
. An empty string is different than null
and is not a valid datetime
value which is why you are getting that error message. You must pass the special sql keyword null
if that's what you mean. Also, don't put any quotes around the word null
. See my insert
statement above for an example of how to insert null
.
EDIT #2: Are you using PDO? If so, when you bind your null param, make sure to use the [PDO::PARAM_NULL][1]
type when binding a null
. See the answer to this stackoverflow question on how to properly insert null
using PDO.
MS Access VBA: Sending an email through Outlook
Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.
Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")
Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing
End Sub
Can't start Tomcat as Windows Service
All those mistakes are related to badly connected Apache and JDK.
- go to start>System>Advanced_system_settings>
- System Properties will pop-up go to Environment Variables
- in User variables you have to set variable: JAVA_HOME value: C:\Program_Files\Java\jdk1.8.0_161
- in System variables you need to put in the path: jdk/bin path & jre/bin path
and also you need to have JAVA_HOME C:\Program_Files\Java\jdk1.8.0_161
people usually forget to setup JAVA_HOME in System variables.
if you still have an error try to think step by step
- Open Event viewer>Check Administrative Events and Windows Logs>System
see the error. If that doesn't help
- go to C:\Program Files\Apache Software Foundation\Tomcat 7.0\logs commons-daemon.XXXX-XX-XX.log
and READ THE ERRORS AND WARNINGS...
there should be nicely put down in words what's the problem.
Loading cross-domain endpoint with AJAX
Your URL
doesn't work these days, but your code can be updated with this working solution:
_x000D_
_x000D_
var url = "http://saskatchewan.univ-ubs.fr:8080/SASStoredProcess/do?_username=DARTIES3-2012&_password=P@ssw0rd&_program=%2FUtilisateurs%2FDARTIES3-2012%2FMon+dossier%2Fanalyse_dc&annee=2012&ind=V&_action=execute";_x000D_
_x000D_
url = 'https://google.com'; // TEST URL_x000D_
_x000D_
$.get("https://images"+~~(Math.random()*33)+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=" + encodeURI(url), function(data) {_x000D_
$('div.ajax-field').html(data);_x000D_
});
_x000D_
<div class="ajax-field"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_
What does %~dp0 mean, and how does it work?
The variable %0
in a batch script is set to the name of the executing batch file.
The ~dp
special syntax between the %
and the 0
basically says to expand the variable %0
to show the drive letter and path, which gives you the current directory containing the batch file!
Help = Link
Writing files in Node.js
Here is the sample of how to read file csv from local and write csv file to local.
var csvjson = require('csvjson'),
fs = require('fs'),
mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient,
mongoDSN = 'mongodb://localhost:27017/test',
collection;
function uploadcsvModule(){
var data = fs.readFileSync( '/home/limitless/Downloads/orders_sample.csv', { encoding : 'utf8'});
var importOptions = {
delimiter : ',', // optional
quote : '"' // optional
},ExportOptions = {
delimiter : ",",
wrap : false
}
var myobj = csvjson.toSchemaObject(data, importOptions)
var exportArr = [], importArr = [];
myobj.forEach(d=>{
if(d.orderId==undefined || d.orderId=='') {
exportArr.push(d)
} else {
importArr.push(d)
}
})
var csv = csvjson.toCSV(exportArr, ExportOptions);
MongoClient.connect(mongoDSN, function(error, db) {
collection = db.collection("orders")
collection.insertMany(importArr, function(err,result){
fs.writeFile('/home/limitless/Downloads/orders_sample1.csv', csv, { encoding : 'utf8'});
db.close();
});
})
}
uploadcsvModule()
SQLite - UPSERT *not* INSERT or REPLACE
Assuming three columns in the table: ID, NAME, ROLE
BAD: This will insert or replace all columns with new values for ID=1:
INSERT OR REPLACE INTO Employee (id, name, role)
VALUES (1, 'John Foo', 'CEO');
BAD: This will insert or replace 2 of the columns... the NAME column will be set to NULL or the default value:
INSERT OR REPLACE INTO Employee (id, role)
VALUES (1, 'code monkey');
GOOD: Use SQLite On conflict clause
UPSERT support in SQLite! UPSERT syntax was added to SQLite with version 3.24.0!
UPSERT is a special syntax addition to INSERT that causes the INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint. UPSERT is not standard SQL. UPSERT in SQLite follows the syntax established by PostgreSQL.
GOOD but tendous: This will update 2 of the columns.
When ID=1 exists, the NAME will be unaffected.
When ID=1 does not exist, the name will be the default (NULL).
INSERT OR REPLACE INTO Employee (id, role, name)
VALUES ( 1,
'code monkey',
(SELECT name FROM Employee WHERE id = 1)
);
This will update 2 of the columns.
When ID=1 exists, the ROLE will be unaffected.
When ID=1 does not exist, the role will be set to 'Benchwarmer' instead of the default value.
INSERT OR REPLACE INTO Employee (id, name, role)
VALUES ( 1,
'Susan Bar',
COALESCE((SELECT role FROM Employee WHERE id = 1), 'Benchwarmer')
);
How to write "Html.BeginForm" in Razor
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
Installing Java 7 (Oracle) in Debian via apt-get
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
What is FCM token in Firebase?
Here is simple steps
add this gradle:
dependencies {
compile "com.google.firebase:firebase-messaging:9.0.0"
}
No extra permission are needed in manifest like GCM.
No receiver is needed to manifest like GCM. With FCM, com.google.android.gms.gcm.GcmReceiver
is added automatically.
Migrate your listener service
A service extending InstanceIDListenerService
is now required only if you want to access the FCM token.
This is needed if you want to
- Manage device tokens to send a messages to single device directly, or
Send messages to device group, or
- Send messages to device group, or
- Subscribe devices to topics with the server subscription management API.
Add Service in manifest
<service
android:name=".MyInstanceIDListenerService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
</intent-filter>
</service>
<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
Change MyInstanceIDListenerService
to extend FirebaseInstanceIdService
, and update code to listen for token updates and get the token whenever a new token is generated.
public class MyInstanceIDListenerService extends FirebaseInstanceIdService {
...
/**
* Called if InstanceID token is updated. This may occur if the security of
* the previous token had been compromised. Note that this is also called
* when the InstanceID token is initially generated, so this is where
* you retrieve the token.
*/
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);
// TODO: Implement this method to send any registration to your app's servers.
sendRegistrationToServer(refreshedToken);
}
}
For more information visit
- How to import former GCM Projects into Firebase
- How to force a token refresh
- How to access the token
- How to set up firebase
CUDA incompatible with my gcc version
If using cmake
for me none of the hacks of editing the files and linking worked so I compiled using the flags which specify the gcc/g++ version.
cmake -DCMAKE_C_COMPILER=gcc-6 -DCMAKE_CXX_COMPILER=g++-6 ..
Worked like charm.
What characters are allowed in an email address?
The short answer is that there are 2 answers. There is one standard for what you should do. ie behaviour that is wise and will keep you out of trouble. There is another (much broader) standard for the behaviour you should accept without making trouble. This duality works for sending and accepting email but has broad application in life.
For a good guide to the addresses you create; see: http://www.remote.org/jochen/mail/info/chars.html
To filter valid emails, just pass on anything comprehensible enough to see a next step.
Or start reading a bunch of RFCs, caution, here be dragons.
How to unzip files programmatically in Android?
Here is a ZipFileIterator (like a java Iterator, but for zip files):
package ch.epfl.bbp.io;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipFileIterator implements Iterator<File> {
private byte[] buffer = new byte[1024];
private FileInputStream is;
private ZipInputStream zis;
private ZipEntry ze;
public ZipFileIterator(File file) throws FileNotFoundException {
is = new FileInputStream(file);
zis = new ZipInputStream(new BufferedInputStream(is));
}
@Override
public boolean hasNext() {
try {
return (ze = zis.getNextEntry()) != null;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
public File next() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int count;
String filename = ze.getName();
File tmpFile = File.createTempFile(filename, "tmp");
tmpFile.deleteOnExit();// TODO make it configurable
FileOutputStream fout = new FileOutputStream(tmpFile);
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
zis.closeEntry();
return tmpFile;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void remove() {
throw new RuntimeException("not implemented");
}
public void close() {
try {
zis.close();
is.close();
} catch (IOException e) {// nope
}
}
}
Using Transactions or SaveChanges(false) and AcceptAllChanges()?
With the Entity Framework most of the time SaveChanges()
is sufficient. This creates a transaction, or enlists in any ambient transaction, and does all the necessary work in that transaction.
Sometimes though the SaveChanges(false) + AcceptAllChanges()
pairing is useful.
The most useful place for this is in situations where you want to do a distributed transaction across two different Contexts.
I.e. something like this (bad):
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save and discard changes
context1.SaveChanges();
//Save and discard changes
context2.SaveChanges();
//if we get here things are looking good.
scope.Complete();
}
If context1.SaveChanges()
succeeds but context2.SaveChanges()
fails the whole distributed transaction is aborted. But unfortunately the Entity Framework has already discarded the changes on context1
, so you can't replay or effectively log the failure.
But if you change your code to look like this:
using (TransactionScope scope = new TransactionScope())
{
//Do something with context1
//Do something with context2
//Save Changes but don't discard yet
context1.SaveChanges(false);
//Save Changes but don't discard yet
context2.SaveChanges(false);
//if we get here things are looking good.
scope.Complete();
context1.AcceptAllChanges();
context2.AcceptAllChanges();
}
While the call to SaveChanges(false)
sends the necessary commands to the database, the context itself is not changed, so you can do it again if necessary, or you can interrogate the ObjectStateManager
if you want.
This means if the transaction actually throws an exception you can compensate, by either re-trying or logging state of each contexts ObjectStateManager
somewhere.
See my blog post for more.
How to get a specific output iterating a hash in Ruby?
Calling sort on a hash converts it into nested arrays and then sorts them by key, so all you need is this:
puts h.sort.map {|k,v| ["#{k}----"] + v}
And if you don't actually need the "----" part, it can be just:
puts h.sort
How do I check whether input string contains any spaces?
This is tested in android 7.0 up to android 10.0 and it works
Use these codes to check if string contains space/spaces may it be in the first position, middle or last:
name = firstname.getText().toString(); //name is the variable that holds the string value
Pattern space = Pattern.compile("\\s+");
Matcher matcherSpace = space.matcher(name);
boolean containsSpace = matcherSpace.find();
if(constainsSpace == true){
//string contains space
}
else{
//string does not contain any space
}
In Java, what is the best way to determine the size of an object?
I doubt you want to do it programmatically unless you just want to do it once and store it for future use. It's a costly thing to do. There's no sizeof() operator in Java, and even if there was, it would only count the cost of the references to other objects and the size of the primitives.
One way you could do it is to serialize the thing to a File and look at the size of the file, like this:
Serializable myObject;
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("obj.ser"));
oos.write (myObject);
oos.close ();
Of course, this assumes that each object is distinct and doesn't contain non-transient references to anything else.
Another strategy would be to take each object and examine its members by reflection and add up the sizes (boolean & byte = 1 byte, short & char = 2 bytes, etc.), working your way down the membership hierarchy. But that's tedious and expensive and ends up doing the same thing the serialization strategy would do.
Is there a way to override class variables in Java?
No. Class variables(Also applicable to instance variables) don't exhibit overriding feature in Java as class variables are invoked on the basis of the type of calling object. Added one more class(Human) in the hierarchy to make it more clear. So now we have
Son extends Dad extends Human
In the below code, we try to iterate over an array of Human, Dad and Son objects, but it prints Human Class’s values in all cases as the type of calling object was Human.
class Human
{
static String me = "human";
public void printMe()
{
System.out.println(me);
}
}
class Dad extends Human
{
static String me = "dad";
}
class Son extends Dad
{
static String me = "son";
}
public class ClassVariables {
public static void main(String[] abc) {
Human[] humans = new Human[3];
humans[0] = new Human();
humans[1] = new Dad();
humans[2] = new Son();
for(Human human: humans) {
System.out.println(human.me); // prints human for all objects
}
}
}
Will print
So no overriding of Class variables.
If we want to access the class variable of actual object from a reference variable of its parent class, we need to explicitly tell this to compiler by casting parent reference (Human object) to its type.
System.out.println(((Dad)humans[1]).me); // prints dad
System.out.println(((Son)humans[2]).me); // prints son
Will print
On how part of this question:- As already suggested override the printMe() method in Son class, then on calling
Son().printMe();
Dad's Class variable "me" will be hidden because the nearest declaration(from Son class printme() method) of the "me"(in Son class) will get the precedence.
Unpivot with column name
Your query is very close. You should be able to use the following which includes the subject
in the final select list:
select u.name, u.subject, u.marks
from student s
unpivot
(
marks
for subject in (Maths, Science, English)
) u;
See SQL Fiddle with demo
Dictionary of dictionaries in Python?
Using collections.defaultdict
is a big time-saver when you're building dicts and don't know beforehand which keys you're going to have.
Here it's used twice: for the resulting dict, and for each of the values in the dict.
import collections
def aggregate_names(errors):
result = collections.defaultdict(lambda: collections.defaultdict(list))
for real_name, false_name, location in errors:
result[real_name][false_name].append(location)
return result
Combining this with your code:
dictionary = aggregate_names(previousFunction(string))
Or to test:
EXAMPLES = [
('Fred', 'Frad', 123),
('Jim', 'Jam', 100),
('Fred', 'Frod', 200),
('Fred', 'Frad', 300)]
print aggregate_names(EXAMPLES)
How can I check if a View exists in a Database?
If you want to check the validity and consistency of all the existing views you can use the following query
declare @viewName sysname
declare @cmd sysname
DECLARE check_cursor CURSOR FOR
SELECT cast('['+SCHEMA_NAME(schema_id)+'].['+name+']' as sysname) AS viewname
FROM sys.views
OPEN check_cursor
FETCH NEXT FROM check_cursor
INTO @viewName
WHILE @@FETCH_STATUS = 0
BEGIN
set @cmd='select * from '+@viewName
begin try
exec (@cmd)
end try
begin catch
print 'Error: The view '+@viewName+' is corrupted .'
end catch
FETCH NEXT FROM check_cursor
INTO @viewName
END
CLOSE check_cursor;
DEALLOCATE check_cursor;
How to submit http form using C#
I needed to have a button handler that created a form post to another application within the client's browser. I landed on this question but didn't see an answer that suited my scenario. This is what I came up with:
protected void Button1_Click(object sender, EventArgs e)
{
var formPostText = @"<html><body><div>
<form method=""POST"" action=""OtherLogin.aspx"" name=""frm2Post"">
<input type=""hidden"" name=""field1"" value=""" + TextBox1.Text + @""" />
<input type=""hidden"" name=""field2"" value=""" + TextBox2.Text + @""" />
</form></div><script type=""text/javascript"">document.frm2Post.submit();</script></body></html>
";
Response.Write(formPostText);
}
How can we print line numbers to the log in java
Quick and dirty way:
System.out.println("I'm in line #" +
new Exception().getStackTrace()[0].getLineNumber());
With some more details:
StackTraceElement l = new Exception().getStackTrace()[0];
System.out.println(
l.getClassName()+"/"+l.getMethodName()+":"+l.getLineNumber());
That will output something like this:
com.example.mytest.MyClass/myMethod:103
How to create a directive with a dynamic template in AngularJS?
I have been in the same situation, my complete solution has been posted here
Basically I load a template in the directive in this way
var tpl = '' +
<div ng-if="maxLength"
ng-include="\'length.tpl.html\'">
</div>' +
'<div ng-if="required"
ng-include="\'required.tpl.html\'">
</div>';
then according to the value of maxLength
and required
I can dynamically load one of the 2 templates, only one of them at a time is shown if necessary.
I heope it helps.
Get MD5 hash of big files in Python
import hashlib,re
opened = open('/home/parrot/pass.txt','r')
opened = open.readlines()
for i in opened:
strip1 = i.strip('\n')
hash_object = hashlib.md5(strip1.encode())
hash2 = hash_object.hexdigest()
print hash2
Proper MIME type for OTF fonts
Ignore the chrome warning. There is no standard MIME type for OTF fonts.
font/opentype may silence the warning, but that doesn't make it the "right" thing to do.
Arguably, you're better off making one up, e.g. with "application/x-opentype" because at least "application" is a registered content type, while "font" is not.
Update: OTF remains a problem, but WOFF grew an IANA MIME type of application/font-woff in January 2013.
Update 2: OTF has grown a MIME type: application/font-sfnt In March 2013. This type also applies to .ttf
cleanup php session files
cd to sessions directory and then:
1) View sessions older than 40 min:
find . -amin +40 -exec stat -c "%n %y" {} \;
2) Remove sessions older than 40 min:
find . -amin +40 -exec rm {} \;
Cannot simply use PostgreSQL table name ("relation does not exist")
I had the same issue as above and I am using PostgreSQL 10.5.
I tried everything as above but nothing seems to be working.
Then I closed the pgadmin and opened a session for the PSQL terminal.
Logged into the PSQL and connected to the database and schema respectively :
\c <DATABASE_NAME>;
set search_path to <SCHEMA_NAME>;
Then, restarted the pgadmin console and then I was able to work without issue in the query-tool of the pagadmin.
Converting a string to a date in DB2
Okay, seems like a bit of a hack. I have got it to work using a substring, so that only the part of the string with the date (not the time) gets passed into the DATE function...
DATE(substr(SETTLEMENTDATE.VALUE,7,4)||'-'|| substr(SETTLEMENTDATE.VALUE,4,2)||'-'|| substr(SETTLEMENTDATE.VALUE,1,2))
I will still accept any answers that are better than this one!
dbms_lob.getlength() vs. length() to find blob size in oracle
length
and dbms_lob.getlength
return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength
will return the number of bytes, which may differ from the number of characters in a multi-byte character set.
As the documentation doesn't specify what happens when you apply length
on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength
.
Create instance of generic type in Java?
Java unfortunatly does not allow what you want to do. See the official workaround :
You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:
public static <E> void append(List<E> list) {
E elem = new E(); // compile-time error
list.add(elem);
}
As a workaround, you can create an object of a type parameter through reflection:
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
E elem = cls.newInstance(); // OK
list.add(elem);
}
You can invoke the append method as follows:
List<String> ls = new ArrayList<>();
append(ls, String.class);
How to find which columns contain any NaN value in Pandas dataframe
UPDATE: using Pandas 0.22.0
Newer Pandas versions have new methods 'DataFrame.isna()' and 'DataFrame.notna()'
In [71]: df
Out[71]:
a b c
0 NaN 7.0 0
1 0.0 NaN 4
2 2.0 NaN 4
3 1.0 7.0 0
4 1.0 3.0 9
5 7.0 4.0 9
6 2.0 6.0 9
7 9.0 6.0 4
8 3.0 0.0 9
9 9.0 0.0 1
In [72]: df.isna().any()
Out[72]:
a True
b True
c False
dtype: bool
as list of columns:
In [74]: df.columns[df.isna().any()].tolist()
Out[74]: ['a', 'b']
to select those columns (containing at least one NaN
value):
In [73]: df.loc[:, df.isna().any()]
Out[73]:
a b
0 NaN 7.0
1 0.0 NaN
2 2.0 NaN
3 1.0 7.0
4 1.0 3.0
5 7.0 4.0
6 2.0 6.0
7 9.0 6.0
8 3.0 0.0
9 9.0 0.0
OLD answer:
Try to use isnull():
In [97]: df
Out[97]:
a b c
0 NaN 7.0 0
1 0.0 NaN 4
2 2.0 NaN 4
3 1.0 7.0 0
4 1.0 3.0 9
5 7.0 4.0 9
6 2.0 6.0 9
7 9.0 6.0 4
8 3.0 0.0 9
9 9.0 0.0 1
In [98]: pd.isnull(df).sum() > 0
Out[98]:
a True
b True
c False
dtype: bool
or as @root proposed clearer version:
In [5]: df.isnull().any()
Out[5]:
a True
b True
c False
dtype: bool
In [7]: df.columns[df.isnull().any()].tolist()
Out[7]: ['a', 'b']
to select a subset - all columns containing at least one NaN
value:
In [31]: df.loc[:, df.isnull().any()]
Out[31]:
a b
0 NaN 7.0
1 0.0 NaN
2 2.0 NaN
3 1.0 7.0
4 1.0 3.0
5 7.0 4.0
6 2.0 6.0
7 9.0 6.0
8 3.0 0.0
9 9.0 0.0
Is there an alternative to string.Replace that is case-insensitive?
Kind of a confusing group of answers, in part because the title of the question is actually much larger than the specific question being asked. After reading through, I'm not sure any answer is a few edits away from assimilating all the good stuff here, so I figured I'd try to sum.
Here's an extension method that I think avoids the pitfalls mentioned here and provides the most broadly applicable solution.
public static string ReplaceCaseInsensitiveFind(this string str, string findMe,
string newValue)
{
return Regex.Replace(str,
Regex.Escape(findMe),
Regex.Replace(newValue, "\\$[0-9]+", @"$$$0"),
RegexOptions.IgnoreCase);
}
So...
- This is an extension method @MarkRobinson
- This doesn't try to skip Regex @Helge (you really have to do byte-by-byte if you want to string sniff like this outside of Regex)
- Passes @MichaelLiu 's excellent test case,
"œ".ReplaceCaseInsensitiveFind("oe", "")
, though he may have had a slightly different behavior in mind.
Unfortunately, @HA 's comment that you have to Escape
all three isn't correct. The initial value and newValue
doesn't need to be.
Note: You do, however, have to escape $
s in the new value that you're inserting if they're part of what would appear to be a "captured value" marker. Thus the three dollar signs in the Regex.Replace inside the Regex.Replace [sic]. Without that, something like this breaks...
"This is HIS fork, hIs spoon, hissssssss knife.".ReplaceCaseInsensitiveFind("his", @"he$0r")
Here's the error:
An unhandled exception of type 'System.ArgumentException' occurred in System.dll
Additional information: parsing "The\hisr\ is\ he\HISr\ fork,\ he\hIsr\ spoon,\ he\hisrsssssss\ knife\." - Unrecognized escape sequence \h.
Tell you what, I know folks that are comfortable with Regex feel like their use avoids errors, but I'm often still partial to byte sniffing strings (but only after having read Spolsky on encodings) to be absolutely sure you're getting what you intended for important use cases. Reminds me of Crockford on "insecure regular expressions" a little. Too often we write regexps that allow what we want (if we're lucky), but unintentionally allow more in (eg, Is $10
really a valid "capture value" string in my newValue regexp, above?) because we weren't thoughtful enough. Both methods have value, and both encourage different types of unintentional errors. It's often easy to underestimate complexity.
That weird $
escaping (and that Regex.Escape
didn't escape captured value patterns like $0
as I would have expected in replacement values) drove me mad for a while. Programming Is Hard (c) 1842
Error in strings.xml file in Android
1. for error: unescaped apostrophe in string
what I found is that AAPT2 tool points to wrong row in xml, sometimes.
So you should correct whole strings.xml file
In Android Studio, in problem file use :
Edit->find->replace
Then write in first field \' (or \&,>,\<,\")
in second put '(or &,>,<,")
then replace each if needed.(or "reptlace all" in case with ')
Then in first field again put '(or &,>,<,")
and in second write \'
then replace each if needed.(or "replace all" in case with ')
2. for other problematic symbols
I use to comment each next half part +rebuild
until i won't find the wrong sign.
E.g. an escaped word "\update" unexpectedly drops such error :)
Map a 2D array onto a 1D array
It's important to store the data in a way that it can be retrieved in the languages used. C-language stores in row-major order (all of first row comes first, then all of second row,...) with every index running from 0 to it's dimension-1. So the order of array x[2][3] is x[0][0], x[0][1], x[0][2], x[1][0], x[1][1], x[1][2]. So in C language, x[i][j] is stored the same place as a 1-dimensional array entry x1dim[ i*3 +j]. If the data is stored that way, it is easy to retrieve in C language.
Fortran and MATLAB are different. They store in column-major order (all of first column comes first, then all of second row,...) and every index runs from 1 to it's dimension. So the index order is the reverse of C and all the indices are 1 greater. If you store the data in the C language order, FORTRAN can find X_C_language[i][j] using X_FORTRAN(j+1, i+1). For instance, X_C_language[1][2] is equal to X_FORTRAN(3,2). In 1-dimensional arrays, that data value is at X1dim_C_language[2*Cdim2 + 3], which is the same position as X1dim_FORTRAN(2*Fdim1 + 3 + 1). Remember that Cdim2 = Fdim1 because the order of indices is reversed.
MATLAB is the same as FORTRAN. Ada is the same as C except the indices normally start at 1. Any language will have the indices in one of those C or FORTRAN orders and the indices will start at 0 or 1 and can be adjusted accordingly to get at the stored data.
Sorry if this explanation is confusing, but I think it is accurate and important for a programmer to know.
How can I replace newlines using PowerShell?
If you want to remove all new line characters and replace them with some character (say comma) then you can use the following.
(Get-Content test.txt) -join ","
This works because Get-Content returns array of lines. You can see it as tokenize function available in many languages.
How do I put hint in a asp:textbox
Adding placeholder attributes from code-behind:
txtFilterTerm.Attributes.Add("placeholder", "Filter" + Filter.Name);
Or
txtFilterTerm.Attributes["placeholder"] = "Filter" + Filter.Name;
Adding placeholder attributes from aspx Page
<asp:TextBox type="text" runat="server" id="txtFilterTerm" placeholder="Filter" />
Or
<input type="text" id="txtFilterTerm" placeholder="Filter"/>
How to monitor Java memory usage?
There are tools that let you monitor the VM's memory usage. The VM can expose memory statistics using JMX. You can also print GC statistics to see how the memory is performing over time.
Invoking System.gc() can harm the GC's performance because objects will be prematurely moved from the new to old generations, and weak references will be cleared prematurely. This can result in decreased memory efficiency, longer GC times, and decreased cache hits (for caches that use weak refs). I agree with your consultant: System.gc() is bad. I'd go as far as to disable it using the command line switch.
How to add an image in Tkinter?
Here is an example for Python 3 that you can edit for Python 2 ;)
from tkinter import *
from PIL import ImageTk, Image
from tkinter import filedialog
import os
root = Tk()
root.geometry("550x300+300+150")
root.resizable(width=True, height=True)
def openfn():
filename = filedialog.askopenfilename(title='open')
return filename
def open_img():
x = openfn()
img = Image.open(x)
img = img.resize((250, 250), Image.ANTIALIAS)
img = ImageTk.PhotoImage(img)
panel = Label(root, image=img)
panel.image = img
panel.pack()
btn = Button(root, text='open image', command=open_img).pack()
root.mainloop()
How to insert new cell into UITableView in Swift
For Swift 5
Remove Cell
let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
yourArray.remove(at: buttonTag)
self.tableView.beginUpdates()
self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
self.tableView.endUpdates()
self.tableView.reloadData()// Not mendatory, But In my case its requires
Add new cell
yourArray.append(4)
tableView.beginUpdates()
tableView.insertRows(at: [
(NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
tableView.endUpdates()
What is causing "Unable to allocate memory for pool" in PHP?
Probably is APC related.
For the people having this problem, please specify you .ini settings. Specifically your apc.mmap_file_mask setting.
For file-backed mmap, it should be set to something like:
apc.mmap_file_mask=/tmp/apc.XXXXXX
To mmap directly from /dev/zero, use:
apc.mmap_file_mask=/dev/zero
For POSIX-compliant shared-memory-backed mmap, use:
apc.mmap_file_mask=/apc.shm.XXXXXX
Entity framework linq query Include() multiple children entities
You might find this article of interest which is available at codeplex.com.
The article presents a new way of expressing queries that span multiple tables in the form of declarative graph shapes.
Moreover, the article contains a thorough performance comparison of this new approach with EF queries. This analysis shows that GBQ quickly outperforms EF queries.
HTML tag inside JavaScript
<html>
<body>
<input type="checkbox" id="number1" onclick="number1();">Number 1</br>
<p id="h1"></p>
<script type="text/javascript">
function number1() {
if(document.getElementById('number1').checked) {
document.getElementById("h1").innerHTML = "<h1>Hello member</h1>";
}
}
</script>
</body>
</html>
"Parse Error : There is a problem parsing the package" while installing Android application
Similar issue, using this "borrowed" and slightly modified code:
Intent intent = new Intent(Intent.ACTION_VIEW);
File newApk = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "myapp.apk");
intent.setDataAndType(Uri.fromFile(newApk), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
result = true;
Needed to change the file creation to this (comma instead of plus in the File constructor, was missing '/' after the download directory):
File newApk = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "myapp.apk");
What is an idiomatic way of representing enums in Go?
It's true that the above examples of using const
and iota
are the most idiomatic ways of representing primitive enums in Go. But what if you're looking for a way to create a more fully-featured enum similar to the type you'd see in another language like Java or Python?
A very simple way to create an object that starts to look and feel like a string enum in Python would be:
package main
import (
"fmt"
)
var Colors = newColorRegistry()
func newColorRegistry() *colorRegistry {
return &colorRegistry{
Red: "red",
Green: "green",
Blue: "blue",
}
}
type colorRegistry struct {
Red string
Green string
Blue string
}
func main() {
fmt.Println(Colors.Red)
}
Suppose you also wanted some utility methods, like Colors.List()
, and Colors.Parse("red")
. And your colors were more complex and needed to be a struct. Then you might do something a bit like this:
package main
import (
"errors"
"fmt"
)
var Colors = newColorRegistry()
type Color struct {
StringRepresentation string
Hex string
}
func (c *Color) String() string {
return c.StringRepresentation
}
func newColorRegistry() *colorRegistry {
red := &Color{"red", "F00"}
green := &Color{"green", "0F0"}
blue := &Color{"blue", "00F"}
return &colorRegistry{
Red: red,
Green: green,
Blue: blue,
colors: []*Color{red, green, blue},
}
}
type colorRegistry struct {
Red *Color
Green *Color
Blue *Color
colors []*Color
}
func (c *colorRegistry) List() []*Color {
return c.colors
}
func (c *colorRegistry) Parse(s string) (*Color, error) {
for _, color := range c.List() {
if color.String() == s {
return color, nil
}
}
return nil, errors.New("couldn't find it")
}
func main() {
fmt.Printf("%s\n", Colors.List())
}
At that point, sure it works, but you might not like how you have to repetitively define colors. If at this point you'd like to eliminate that, you could use tags on your struct and do some fancy reflecting to set it up, but hopefully this is enough to cover most people.
How to get parameters from the URL with JSP
example you wanted to delete the subject record with its subject_id
@RequestMapping(value="subject_setup/delete/{subjectid}",method = RequestMethod.GET)
public ModelAndView delete(@PathVariable int subjectid) {
subjectsDao.delete(subjectid);
return new ModelAndView("redirect:/subject_setup");
}
and the parameter will be used for input on your query
public int delete(int subjectid) {
String sql = "update tbl_subject set isdeleted= '1' where id = "+subjectid+"";
return template.update(sql);
}
What does $_ mean in PowerShell?
I think the easiest way to think about this variable like input parameter in lambda expression in C#. I.e. $_
is similar to x
in x => Console.WriteLine(x)
anonymous function in C#. Consider following examples:
PowerShell:
1,2,3 | ForEach-Object {Write-Host $_}
Prints:
1
2
3
or
1,2,3 | Where-Object {$_ -gt 1}
Prints:
2
3
And compare this with C# syntax using LINQ:
var list = new List<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));
Prints:
1
2
3
or
list.Where( _ => _ > 1)
.ToList()
.ForEach(s => Console.WriteLine(s));
Prints:
2
3
Using Selenium Web Driver to retrieve value of a HTML input
This is kind of hacky, but it works.
I used JavascriptExecutor
and added a div
to the HTML, and changed the text in the div
to $('#prettyTime').val()
I then used Selenium to retrieve the div
and grab its value. After testing the correctness of the value, I removed the div that was just created.
How to get to a particular element in a List in java?
The toString
method of array types in Java isn't particularly meaningful, other than telling you what that is an array of.
You can use java.util.Arrays.toString
for that.
Or if your lines only contain numbers, and you want a line as 1,2,3,4...
instead of [1, 2, 3, ...]
, you can use:
java.util.Arrays.toString(someArray).replaceAll("\\]| |\\[","")
Python, creating objects
class Student(object):
name = ""
age = 0
major = ""
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def make_student(name, age, major):
student = Student(name, age, major)
return student
Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:
class Student(object):
name = ""
age = 0
major = ""
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
# Note: I didn't need to create a variable in the class definition before doing this.
student.gpa = float(4.0)
return student
I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.
How to list all users in a Linux group?
The following shell script will iterate through all users and print only those user names which belong to a given group:
#!/usr/bin/env bash
getent passwd | while IFS=: read name trash
do
groups $name 2>/dev/null | cut -f2 -d: | grep -i -q -w "$1" && echo $name
done
true
Usage example:
./script 'DOMAIN+Group Name'
Note: This solution will check NIS and LDAP for users and groups (not only passwd
and group
files). It will also take into account users not added to a group but having group set as primary group.
Edit: Added fix for rare scenario where user does not belong to group with the same name.
Edit: written in the form of a shell script; added true
to exit with 0
status as suggested by @Max Chernyak aka hakunin; discarded stderr
in order to skip those occasional groups: cannot find name for group ID xxxxxx
.
Local and global temporary tables in SQL Server
1.) A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.
Local temp tables are only available to the SQL Server session or
connection (means single user) that created the tables. These are
automatically deleted when the session that created the tables has
been closed. Local temporary table name is stared with single hash
("#") sign.
CREATE TABLE #LocalTemp
(
UserID int,
Name varchar(50),
Address varchar(150)
)
GO
insert into #LocalTemp values ( 1, 'Name','Address');
GO
Select * from #LocalTemp
The scope of Local temp table exist to the current session of current
user means to the current query window. If you will close the current
query window or open a new query window and will try to find above
created temp table, it will give you the error.
2.) A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.
Global temp tables are available to all SQL Server sessions or
connections (means all the user). These can be created by any SQL
Server connection user and these are automatically deleted when all
the SQL Server connections have been closed. Global temporary table
name is stared with double hash ("##") sign.
CREATE TABLE ##GlobalTemp
(
UserID int,
Name varchar(50),
Address varchar(150)
)
GO
insert into ##GlobalTemp values ( 1, 'Name','Address');
GO
Select * from ##GlobalTemp
Global temporary tables are visible to all SQL Server connections
while Local temporary tables are visible to only current SQL Server
connection.
Changing CSS for last <li>
If you know there are three li's in the list you're looking at, for example, you could do this:
li + li + li { /* Selects third to last li */
}
In IE6 you can use expressions:
li {
color: expression(this.previousSibling ? 'red' : 'green'); /* 'green' if last child */
}
I would recommend using a specialized class or Javascript (not IE6 expressions), though, until the :last-child
selector gets better support.
Accessing all items in the JToken
If you know the structure of the json that you're receiving then I'd suggest having a class structure that mirrors what you're receiving in json.
Then you can call its something like this...
AddressMap addressMap = JsonConvert.DeserializeObject<AddressMap>(json);
(Where json is a string containing the json in question)
If you don't know the format of the json you've receiving then it gets a bit more complicated and you'd probably need to manually parse it.
check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx for more info
How to fix error Base table or view not found: 1146 Table laravel relationship table?
If you're facing this error but your issue is different and you're tired of searching for a long time then this might help you.
If you have changed your database and updated .env file and still facing same issue then you should check C:\xampp\htdocs{your-project-name}\bootstrap\cache\config.php file and replace or remove the old database name and other changed items.
Using Bootstrap Tooltip with AngularJS
If you're building an Angular app, you can use jQuery, but there is a lot of good reasons to try to avoid it in favor of more angular driven paradigms. You can continue to use the styles provided by bootstrap, but replace the jQuery plugins with native angular by using UI Bootstrap
Include the Boostrap CSS files, Angular.js, and ui.Bootstrap.js:
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.angularjs.org/1.2.20/angular.js"></script>
<script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.js"></script>
Make sure you've injected ui.bootstrap
when you create your module like this:
var app = angular.module('plunker', ['ui.bootstrap']);
Then you can use angular directives instead of data attributes picked up by jQuery:
<button type="button" class="btn btn-default"
title="Tooltip on left" data-toggle="tooltip" data-placement="left"
tooltip="Tooltip on left" tooltip-placement="left" >
Tooltip on left
</button>
Avoiding UI Bootstrap
jQuery.min.js (94kb) + Bootstrap.min.js (32kb) is also giving you more than you need, and much more than ui-bootstrap.min.js (41kb).
And time spent downloading the modules is only one aspect of performance.
If you really wanted to only load the modules you needed, you can "Create a Build" and choose tooltips from the Bootstrap-UI website. Or you can explore the source code for tooltips and pick out what you need.
Here a minified custom build with just the tooltips and templates (6kb)
Are there any style options for the HTML5 Date picker?
FYI, I needed to update the color of the calendar icon which didn't seem possible with properties like color
, fill
, etc.
I did eventually figure out that some filter
properties will adjust the icon so while i did not end up figuring out how to make it any color, luckily all I needed was to make it so the icon was visible on a dark background so I was able to do the following:
_x000D_
_x000D_
body { background: black; }_x000D_
_x000D_
input[type="date"] { _x000D_
background: transparent;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
filter: invert(100%);_x000D_
}
_x000D_
<body>_x000D_
<input type="date" />_x000D_
</body>
_x000D_
_x000D_
_x000D_
Hopefully this helps some people as for the most part chrome even directly says this is impossible.
What is the difference between encrypting and signing in asymmetric encryption?
In RSA crypto, when you generate a key pair, it's completely arbitrary which one you choose to be the public key, and which is the private key. If you encrypt with one, you can decrypt with the other - it works in both directions.
So, it's fairly simple to see how you can encrypt a message with the receiver's public key, so that the receiver can decrypt it with their private key.
A signature is proof that the signer has the private key that matches some public key. To do this, it would be enough to encrypt the message with that sender's private key, and include the encrypted version alongside the plaintext version. To verify the sender, decrypt the encrypted version, and check that it is the same as the plaintext.
Of course, this means that your message is not secret. Anyone can decrypt it, because the public key is well known. But when they do so, they have proved that the creator of the ciphertext has the corresponding private key.
However, this means doubling the size of your transmission - plaintext and ciphertext together (assuming you want people who aren't interested in verifying the signature, to read the message). So instead, typically a signature is created by creating a hash of the plaintext. It's important that fake hashes can't be created, so cryptographic hash algorithms such as SHA-2 are used.
So:
- To generate a signature, make a hash from the plaintext, encrypt it with your private key, include it alongside the plaintext.
- To verify a signature, make a hash from the plaintext, decrypt the signature with the sender's public key, check that both hashes are the same.
How to run stored procedures in Entity Framework Core?
I'm using Entity Framework Core with my ASP.Net Core 3.x WebAPI. I wanted one of my end points just to execute a particular Stored Procedure, and this is the code I needed:
namespace MikesBank.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ResetController : ControllerBase
{
private readonly MikesBankContext _context;
public ResetController(MikesBankContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult> Get()
{
try
{
using (DbConnection conn = _context.Database.GetDbConnection())
{
if (conn.State != System.Data.ConnectionState.Open)
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = "Reset_Data";
await cmd.ExecuteNonQueryAsync();
}
return new OkObjectResult(1);
}
catch (Exception ex)
{
return new BadRequestObjectResult(ex.Message);
}
}
}
}
Notice how I need to get my DbContext
which has been injected, but I also need to Open()
this connection.
.war vs .ear file
war - web archive. It is used to deploy web applications according to the servlet standard. It is a jar file containing a special directory called WEB-INF and several files and directories inside it (web.xml, lib, classes) as well as all the HTML, JSP, images, CSS, JavaScript and other resources of the web application
ear - enterprise archive. It is used to deploy enterprise application containing EJBs, web applications, and 3rd party libraries. It is also a jar file, it has a special directory called APP-INF that contains the application.xml file, and it contains jar and war files.
Java regular expression OR operator
You can just use the pipe on its own:
"string1|string2"
for example:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));
Output:
blah, blah, string3
The main reason to use parentheses is to limit the scope of the alternatives:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));
has the same output. but if you just do this:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));
you get:
blah, stringblah, string3
because you've said "string1" or "2".
If you don't want to capture that part of the expression use ?:
:
String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));
How can I convert a DateTime to the number of seconds since 1970?
That's basically it. These are the methods I use to convert to and from Unix epoch time:
public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
return origin.AddSeconds(timestamp);
}
public static double ConvertToUnixTimestamp(DateTime date)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
TimeSpan diff = date.ToUniversalTime() - origin;
return Math.Floor(diff.TotalSeconds);
}
Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static DateTime.UnixEpoch
.
Where is the WPF Numeric UpDown control?
Apologize for keep answering 9 years questions.
I have follow @Michael's answer and it works.
I do it as UserControl where I can drag and drop like a Controls elements. I use MaterialDesign Theme from Nuget to get the Chevron icon and button ripple effect.
The running NumericUpDown from Micheal with modification will be as below:-
The code for user control:-
TemplateNumericUpDown.xaml
<UserControl x:Class="UserControlTemplate.TemplateNumericUpDown"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:UserControlTemplate"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
mc:Ignorable="d" MinHeight="48">
<Grid Background="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="60"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtNum" x:FieldModifier="private" Text="{Binding Path=NumValue}" TextChanged="TxtNum_TextChanged" FontSize="36" BorderThickness="0" VerticalAlignment="Center" Padding="5,0"/>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="30*"/>
<RowDefinition Height="30*"/>
</Grid.RowDefinitions>
<Grid Background="#FF673AB7">
<Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto" Width="Auto">
<materialDesign:PackIcon Kind="ChevronUp" Foreground="White" Height="32.941" Width="32"/>
</Viewbox>
<Button x:Name="cmdUp" x:FieldModifier="private" Click="CmdUp_Click" Height="Auto" BorderBrush="{x:Null}" Background="{x:Null}"/>
</Grid>
<Grid Grid.Row="1" Background="#FF673AB7">
<Viewbox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Height="Auto" Width="Auto">
<materialDesign:PackIcon Kind="ChevronDown" Foreground="White" Height="32.942" Width="32"/>
</Viewbox>
<Button x:Name="cmdDown" x:FieldModifier="private" Click="CmdDown_Click" Height="Auto" BorderBrush="{x:Null}" Background="{x:Null}"/>
</Grid>
</Grid>
</Grid>
</UserControl>
TemplateNumericUpDown.cs
using System.Windows;
using System.Windows.Controls;
namespace UserControlTemplate
{
/// <summary>
/// Interaction logic for TemplateNumericUpDown.xaml
/// </summary>
public partial class TemplateNumericUpDown : UserControl
{
private int _numValue = 0;
public TemplateNumericUpDown()
{
InitializeComponent();
txtNum.Text = _numValue.ToString();
}
public int NumValue
{
get { return _numValue; }
set
{
if (value >= 0)
{
_numValue = value;
txtNum.Text = value.ToString();
}
}
}
private void CmdUp_Click(object sender, RoutedEventArgs e)
{
NumValue++;
}
private void CmdDown_Click(object sender, RoutedEventArgs e)
{
NumValue--;
}
private void TxtNum_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtNum == null)
{
return;
}
if (!int.TryParse(txtNum.Text, out _numValue))
txtNum.Text = _numValue.ToString();
}
}
}
On MyPageDesign.xaml, drag and drop created usercontrol will having <UserControlTemplate:TemplateNumericUpDown HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100"/>
To get the value from the template, I use
string Value1 = JournalNumStart.NumValue;
string Value2 = JournalNumEnd.NumValue;
I'm not in good skill yet to binding the Height of the control based from FontSize element, so I set the from my page fontsize manually in usercontrol.
** Note:- I have change the "Archieve" name to Archive on my program =)
Change Project Namespace in Visual Studio
You can change the default namespace:
-> Project
-> XXX Properties...
On Application tab: Default namespace
Other than that:
Ctrl-H
Find: WindowsFormsApplication16
Replace: MyName
Detecting which UIButton was pressed in a UITableView
I would use the tag property like you said, setting the tag like so:
[button setTag:indexPath.row];
then getting the tag inside of the buttonPressedAction like so:
((UIButton *)sender).tag
Or
UIButton *button = (UIButton *)sender;
button.tag;
How to achieve function overloading in C?
In the sense you mean — no, you cannot.
You can declare a va_arg
function like
void my_func(char* format, ...);
, but you'll need to pass some kind of information about number of variables and their types in the first argument — like printf()
does.
CSS 100% height with padding/margin
Border around div, rather than page body margin
Another solution - I just wanted a simple border around the edge of my page, and I wanted 100% height when the content was smaller than that.
Border-box didn't work, and the fixed positioning seemed wrong for such a simple need.
I ended up adding a border to my container, instead of relying on the margin of the body of the page - it looks like this :
body, html {
height: 100%;
margin: 0;
}
.container {
width: 100%;
min-height: 100%;
border: 8px solid #564333;
}
How to add a color overlay to a background image?
background-image
takes multiple values.
so a combination of just 1 color linear-gradient and css blend modes
will do the trick.
.testclass {
background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
background-blend-mode: overlay;
}
note that there is no support on IE/Edge for CSS blend-modes at all.
How would I get a cron job to run every 30 minutes?
crontab does not understand "intervals", it only understands "schedule"
valid hours: 0-23 -- valid minutes: 0-59
example #1
30 * * * * your_command
this means "run when the minute of each hour is 30" (would run at: 1:30, 2:30, 3:30, etc)
example #2
*/30 * * * * your_command
this means "run when the minute of each hour is evenly divisible by 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)
example #3
0,30 * * * * your_command
this means "run when the minute of each hour is 0 or 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)
it's another way to accomplish the same results as example #2
example #4
19 * * * * your_command
this means "run when the minute of each hour is 19" (would run at: 1:19, 2:19, 3:19, etc)
example #5
*/19 * * * * your_command
this means "run when the minute of each hour is evenly divisible by 19" (would run at: 1:19, 1:38, 1:57, 2:19, 2:38, 2:57 etc)
note: several refinements have been made to this post by various users including the author
numpy.where() detailed, step-by-step explanation / examples
After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.
Intuitively, np.where
is like asking "tell me where in this array, entries satisfy a given condition".
>>> a = np.arange(5,10)
>>> np.where(a < 8) # tell me where in a, entries are < 8
(array([0, 1, 2]),) # answer: entries indexed by 0, 1, 2
It can also be used to get entries in array that satisfy the condition:
>>> a[np.where(a < 8)]
array([5, 6, 7]) # selects from a entries 0, 1, 2
When a
is a 2d array, np.where()
returns an array of row idx's, and an array of col idx's:
>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
[7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))
As in the 1d case, we can use np.where()
to get entries in the 2d array that satisfy the condition:
>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2
array([9])
Note, when a
is 1d, np.where()
still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.
How to parse JSON in Java
Jakarta (Java) Enterprise Edition 8 includes the JSON-B (Java API for JSON Binding). So, if you are using a Jakarta EE 8 server, like Payara 5, JSON-B will be available out of the box.
A simple example, without custom configuration:
public static class Dog {
public String name;
public int age;
public boolean bites;
}
// Create a dog instance
Dog dog = new Dog();
dog.name = "Falco";
dog.age = 4;
dog.bites = false;
// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);
// Deserialize back
dog = jsonb.fromJson("{\"name\":\"Falco\",\"age\":4,\"bites\":false}", Dog.class);
You can customize the mapping by using configuration, annotations, adapters and (de)serializers.
If you are not using a Jakarta EE 8 use can always install JSON-B.
Get list of data-* attributes using javascript / jQuery
I use nested each - for me this is the easiest solution (Easy to control/change "what you do with the values - in my example output data-attributes as ul-list
) (Jquery Code)
_x000D_
_x000D_
var model = $(".model");_x000D_
_x000D_
var ul = $("<ul>").appendTo("body");_x000D_
_x000D_
$(model).each(function(index, item) {_x000D_
ul.append($(document.createElement("li")).text($(this).text()));_x000D_
$.each($(this).data(), function(key, value) {_x000D_
ul.append($(document.createElement("strong")).text(key + ": " + value));_x000D_
ul.append($(document.createElement("br")));_x000D_
}); //inner each_x000D_
ul.append($(document.createElement("hr")));_x000D_
}); // outer each_x000D_
_x000D_
/*print html*/_x000D_
var htmlString = $("ul").html();_x000D_
$("code").text(htmlString);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/prism.min.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.17.1/themes/prism-okaidia.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<h1 id="demo"></h1>_x000D_
_x000D_
<ul>_x000D_
<li class="model" data-price="45$" data-location="Italy" data-id="1234">Model 1</li>_x000D_
<li class="model" data-price="75$" data-location="Israel" data-id="4321">Model 2</li> _x000D_
<li class="model" data-price="99$" data-location="France" data-id="1212">Model 3</li> _x000D_
</ul>_x000D_
_x000D_
<pre>_x000D_
<code class="language-html">_x000D_
_x000D_
</code>_x000D_
</pre>_x000D_
_x000D_
<h2>Generate list by code</h2>_x000D_
<br>
_x000D_
_x000D_
_x000D_
Codepen: https://codepen.io/ezra_siton/pen/GRgRwNw?editors=1111
How to tell if a file is git tracked (by shell exit code)?
I suggest a custom alias on you .gitconfig
.
You have to way to do:
1) With git command:
git config --global alias.check-file <command>
2) Editing ~/.gitconfig
and add this line on alias section:
[alias]
check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi; }; f"
Once launched command (1) or saved file (2), on your workspace you can test it:
$ git check-file
$ Filename missing
$ git check-file README.md
$ File tracked
$ git check-file foo
$ File not tracked
Unfinished Stubbing Detected in Mockito
For those who use com.nhaarman.mockitokotlin2.mock {}
This error occurs when, for example, we create a mock inside another mock
mock {
on { x() } doReturn mock {
on { y() } doReturn z()
}
}
The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.
val liveDataMock = mock {
on { y() } doReturn z()
}
mock {
on { x() } doReturn liveDataMock
}
GL
MySQL - length() vs char_length()
varchar(10) will store 10 characters, which may be more than 10 bytes.
In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.
Traversing text in Insert mode
If you are a vim purist, skip reading this answer. OTOH, if you are new to vim and are looking for a few helpful tips you wont find in the many hundred of vim tutorials and blogs, read on... :-)
A few un-orthodox (vim) ways
It's 2014, and as someone who's recently gone back to vim
I can offer a few, potentially contrarian, points of view and tips.
Use shift+left or shift+right to traverse words
While repetition is a powerful concept in vim, I (personally) find it strange that using it either forces me to count (lines, characters, words, etc.) or make guesses. My brain usually works like "I want the cursor there" and not like "I want the cursor _5_words_to_the_left_". Quickly being able to move the cursor, and visually observe where the insertion point this way allows me to keep my mind on what I'm editing instead of having to count how many hops I need to make to get to where I need to edit.
Turn on mouse mode, and use the mouse wheel and clicking
...to navigate large bodies of text.
Most (all) modern computers have a touchpad that is closely integrated with the keyboard (e.g. MacBooks). Industrial designers have spent many man years optimizing these designs so that the old problem of having to move the hand away from the keyboard is no longer a real issue. Okay, it is if you are used to a mouse and don't like to switch, but for anyone new to vim (like those that might find this post via a search), this should not be much of an issue.
As a bonus, click + drag puts you in visual mode
With mouse enabled, clicking and dragging has the effect of switching to visual mode and marking a region for yanking.
And use the scroll wheel
Using the mouse (wheel) to scroll around, and clicking to position the cursor (duh) just works. See http://usevim.com/2012/05/16/mouse/ for more on this.
And so...
These are what I'd call more modern (using mouse, scroll wheel, etc.) ways of navigating in vim, equally effective depending on your preference of input.
HTH
IIS Config Error - This configuration section cannot be used at this path
Follow the below steps to unlock the handlers at the parent level:
1) In the connections tree(in IIS), go to your server node and then to your website.
2) For the website, in the right window you will see configuration editor under Management.
3) Double click on the configuration editor.
4) In the window that opens, on top you will find a drop down for sections. Choose "system.webServer/handlers" from the drop down.
5) On the right side, there is another drop down. Choose "ApplicationHost.Config "
6) On the right most pane, you will find "Unlock Section" under "Section" heading. Click on that.
7) Once the handlers at the applicationHost is unlocked, your website should run fine.
Long press on UITableView
Answer in Swift:
Add delegate UIGestureRecognizerDelegate
to your UITableViewController.
Within UITableViewController:
override func viewDidLoad() {
super.viewDidLoad()
let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
longPressGesture.minimumPressDuration = 1.0 // 1 second press
longPressGesture.delegate = self
self.tableView.addGestureRecognizer(longPressGesture)
}
And the function:
func handleLongPress(longPressGesture:UILongPressGestureRecognizer) {
let p = longPressGesture.locationInView(self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(p)
if indexPath == nil {
print("Long press on table view, not row.")
}
else if (longPressGesture.state == UIGestureRecognizerState.Began) {
print("Long press on row, at \(indexPath!.row)")
}
}
Best practice to look up Java Enum
update: As GreenTurtle correctly remarked, the following is wrong
I would just write
boolean result = Arrays.asList(FooEnum.values()).contains("Foo");
This is possibly less performant than catching a runtime exception, but makes for much cleaner code. Catching such exceptions is always a bad idea, since it is prone to misdiagnosis.
What happens when the retrieval of the compared value itself causes an IllegalArgumentException ? This would then be treaten like a non matching value for the enumerator.
Set order of columns in pandas dataframe
Try indexing (so you want a generic solution not only for this, so index order can be just what you want):
l=[0,2,1] # index order
frame=frame[[frame.columns[i] for i in l]]
Now:
print(frame)
Is:
one thing second thing other thing
0 1 0.1 a
1 2 0.2 e
2 3 1.0 i
3 4 2.0 o
SOAP or REST for Web Services?
I'd recommend you go with REST first - if you're using Java look at JAX-RS and the Jersey implementation. REST is much simpler and easy to interop in many languages.
As others have said in this thread, the problem with SOAP is its complexity when the other WS-* specifications come in and there are countless interop issues if you stray into the wrong parts of WSDL, XSDs, SOAP, WS-Addressing etc.
The best way to judge the REST v SOAP debate is look on the internet - pretty much all the big players in the web space, google, amazon, ebay, twitter et al - tend to use and prefer RESTful APIs over the SOAP ones.
The other nice approach to going with REST is that you can reuse lots of code and infratructure between a web application and a REST front end. e.g. rendering HTML versus XML versus JSON of your resources is normally pretty easy with frameworks like JAX-RS and implicit views - plus its easy to work with RESTful resources using a web browser
Finding Number of Cores in Java
If you want to dubbel check the amount of cores you have on your machine to the number your java program is giving you.
In Linux terminal: lscpu
In Windows terminal (cmd): echo %NUMBER_OF_PROCESSORS%
In Mac terminal: sysctl -n hw.ncpu
Iterate through a C++ Vector using a 'for' loop
With STL, programmers use iterators
for traversing through containers, since iterator is an abstract concept, implemented in all standard containers. For example, std::list
has no operator []
at all.
Twitter API returns error 215, Bad Authentication Data
FOUND A SOLUTION - using the Abraham TwitterOAuth library. If you are using an older implementation, the following lines should be added after the new TwitterOAuth object is instantiated:
$connection->host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
The first 2 lines are now documented in Abraham library Readme file, but the 3rd one is not. Also make sure that your oauth_version is still 1.0.
Here is my code for getting all user data from 'users/show' with a newly authenticated user and returning the user full name and user icon with 1.1 - the following code is implemented in the authentication callback file:
session_start();
require ('twitteroauth/twitteroauth.php');
require ('twitteroauth/config.php');
$consumer_key = '****************';
$consumer_secret = '**********************************';
$to = new TwitterOAuth($consumer_key, $consumer_secret);
$tok = $to->getRequestToken('http://exampleredirect.com?twitoa=1');
$token = $tok['oauth_token'];
$secret = $tok['oauth_token_secret'];
//save tokens to session
$_SESSION['ttok'] = $token;
$_SESSION['tsec'] = $secret;
$request_link = $to->getAuthorizeURL($token,TRUE);
header('Location: ' . $request_link);
The following code then is in the redirect after authentication and token request
if($_REQUEST['twitoa']==1){
require ('twitteroauth/twitteroauth.php');
require_once('twitteroauth/config.php');
//Twitter Creds
$consumer_key = '*****************';
$consumer_secret = '************************************';
$oauth_token = $_GET['oauth_token']; //ex Request vals->http://domain.com/twitter_callback.php?oauth_token=MQZFhVRAP6jjsJdTunRYPXoPFzsXXKK0mQS3SxhNXZI&oauth_verifier=A5tYHnAsbxf3DBinZ1dZEj0hPgVdQ6vvjBJYg5UdJI
$ttok = $_SESSION['ttok'];
$tsec = $_SESSION['tsec'];
$to = new TwitterOAuth($consumer_key, $consumer_secret, $ttok, $tsec);
$tok = $to->getAccessToken();
$btok = $tok['oauth_token'];
$bsec = $tok['oauth_token_secret'];
$twit_u_id = $tok['user_id'];
$twit_screen_name = $tok['screen_name'];
//Twitter 1.1 DEBUG
//print_r($tok);
//echo '<br/><br/>';
//print_r($to);
//echo '<br/><br/>';
//echo $btok . '<br/><br/>';
//echo $bsec . '<br/><br/>';
//echo $twit_u_id . '<br/><br/>';
//echo $twit_screen_name . '<br/><br/>';
$twit_screen_name=urlencode($twit_screen_name);
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $btok, $bsec);
$connection->host = "https://api.twitter.com/1.1/";
$connection->ssl_verifypeer = TRUE;
$connection->content_type = 'application/x-www-form-urlencoded';
$ucontent = $connection->get('users/show', array('screen_name' => $twit_screen_name));
//echo 'connection:<br/><br/>';
//print_r($connection);
//echo '<br/><br/>';
//print_r($ucontent);
$t_user_name = $ucontent->name;
$t_user_icon = $ucontent->profile_image_url;
//echo $t_user_name.'<br/><br/>';
//echo $t_user_icon.'<br/><br/>';
}
It took me way too long to figure this one out. Hope this helps someone!!
How to split/partition a dataset into training and test datasets for, e.g., cross validation?
If you want to split the data set once in two halves, you can use numpy.random.shuffle
, or numpy.random.permutation
if you need to keep track of the indices:
import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
numpy.random.shuffle(x)
training, test = x[:80,:], x[80:,:]
or
import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
indices = numpy.random.permutation(x.shape[0])
training_idx, test_idx = indices[:80], indices[80:]
training, test = x[training_idx,:], x[test_idx,:]
There are many ways to repeatedly partition the same data set for cross validation. One strategy is to resample from the dataset, with repetition:
import numpy
# x is your dataset
x = numpy.random.rand(100, 5)
training_idx = numpy.random.randint(x.shape[0], size=80)
test_idx = numpy.random.randint(x.shape[0], size=20)
training, test = x[training_idx,:], x[test_idx,:]
Finally, sklearn contains several cross validation methods (k-fold, leave-n-out, ...). It also includes more advanced "stratified sampling" methods that create a partition of the data that is balanced with respect to some features, for example to make sure that there is the same proportion of positive and negative examples in the training and test set.
Inserting values into a SQL Server database using ado.net via C#
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source=CHANCHAL\SQLEXPRESS;initial catalog=AssetManager;user id=GIPL-PC\GIPL;password=";
con.Open();
SqlDataAdapter ad = new SqlDataAdapter("select * from detail1", con);
SqlCommandBuilder cmdbl = new SqlCommandBuilder(ad);
DataSet ds = new DataSet("detail1");
ad.Fill(ds, "detail1");
DataRow row = ds.Tables["detail1"].NewRow();
row["Name"] = textBox1.Text;
row["address"] =textBox2.Text;
ds.Tables["detail1"].Rows.Add(row);
ad.Update(ds, "detail1");
con.Close();
MessageBox.Show("insert secussfully");
}
Difference between java HH:mm and hh:mm on SimpleDateFormat
kk: (01-24) will look like 01, 02..24.
HH:(00-23) will look like 00, 01..23.
hh:(01-12 in AM/PM) will look like 01, 02..12.
so the last printout (working2
) is a bit weird. It should say 12:00:00
(edit: if you were setting the working2
timezone and format, which (as kdagli pointed out) you are not)
How to count the NaN values in a column in pandas DataFrame
For the 1st part count NaN
we have multiple way.
Method 1 count
, due to the count
will ignore the NaN
which is different from size
print(len(df) - df.count())
Method 2 isnull
/ isna
chain with sum
print(df.isnull().sum())
#print(df.isna().sum())
Method 3 describe
/ info
: notice this will output the 'notnull' value count
print(df.describe())
#print(df.info())
Method from numpy
print(np.count_nonzero(np.isnan(df.values),axis=0))
For the 2nd part of the question, If we would like drop the column by the thresh,we can try with dropna
thresh, optional Require that many non-NA values.
Thresh = n # no null value require, you can also get the by int(x% * len(df))
df = df.dropna(thresh = Thresh, axis = 1)
how to pass variable from shell script to sqlplus
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
Check if a string within a list contains a specific string with Linq
If yoou use Contains, you could get false positives.
Suppose you have a string that contains such text: "My text data Mdd LH"
Using Contains method, this method will return true for call.
The approach is use equals operator:
bool exists = myStringList.Any(c=>c == "Mdd LH")
How can I move all the files from one folder to another using the command line?
move c:\sourcefolder c:\targetfolder
will work, but you will end up with a structure like this:
c:\targetfolder\sourcefolder\[all the subfolders & files]
If you want to move just the contents of one folder to another, then this should do it:
SET src_folder=c:\srcfold
SET tar_folder=c:\tarfold
for /f %%a IN ('dir "%src_folder%" /b') do move "%src_folder%\%%a" "%tar_folder%\"
pause
Convert integer to hex and hex to integer
Declare @Dato xml
Set @Dato = Convert(xml, '<dato>FF</dato>')
Select Cast( rw.value( 'xs:hexBinary( text()[1])' , 'varbinary(max)' ) as int ) From @Dato.nodes('dato') as T(rw)
Can I set an opacity only to the background image of a div?
<!DOCTYPE html>
<html>
<head></head>
<body>
<div style=" background-color: #00000088"> Hi there </div>
<!-- #00 would be r, 00 would be g, 00 would be b, 88 would be a. -->
</body>
</html>
including 4 sets of numbers would make it rgba, not cmyk, but either way would work (rgba= 00000088, cmyk= 0%, 0%, 0%, 50%)
How to send value attribute from radio button in PHP
Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it:
The PHP code:
<?PHP
$male_status = 'unchecked';
$female_status = 'unchecked';
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
if ($selected_radio == 'male') {
$male_status = 'checked';
}else if ($selected_radio == 'female') {
$female_status = 'checked';
}
}
?>
The HTML FORM code:
<FORM name ="form1" method ="post" action ="radioButton.php">
<Input type = 'Radio' Name ='gender' value= 'male'
<?PHP print $male_status; ?>
>Male
<Input type = 'Radio' Name ='gender' value= 'female'
<?PHP print $female_status; ?>
>Female
<P>
<Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
</FORM>
Add new row to excel Table (VBA)
Just delete the table and create a new table with a different name. Also Don't delete entire row for that table. It seems when entire row containing table row is delete it damages the DataBodyRange is damaged
Multiple aggregate functions in HAVING clause
select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0
EOFException - how to handle?
Put your code inside the try catch block:
i.e :
try{
if(in.available()!=0){
// ------
}
}catch(EOFException eof){
//
}catch(Exception e){
//
}
}
How to install "ifconfig" command in my ubuntu docker image?
From within a Dockerfile something like the following should do the trick:
RUN apt-get update && \
apt-get install -y net-tools
From memory it's best practice to combine the update and the package installation lines to prevent docker caching the update step which can result in out-dated packages being installed.
Installing it via the CLI or a shell script:
apt-get update && apt-get install net-tools
How to display binary data as image - extjs 4
Need to convert it in base64.
JS have btoa() function for it.
For example:
var img = document.createElement('img');
img.src = 'data:image/jpeg;base64,' + btoa('your-binary-data');
document.body.appendChild(img);
But i think what your binary data in pastebin is invalid - the jpeg data must be ended on 'ffd9'.
Update:
Need to write simple hex to base64 converter:
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}
And use it:
img.src = 'data:image/jpeg;base64,' + hexToBase64('your-binary-data');
See working example with your hex data on jsfiddle
Swift Open Link in Safari
Swift 3 & IOS 10.2
UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
Swift 3 & IOS 10.2
How to use a filter in a controller?
function ngController($scope,$filter){
$scope.name = "aaaa";
$scope.age = "32";
$scope.result = function(){
return $filter('lowercase')($scope.name);
};
}
The controller method 2nd argument name should be "$filter" then only the filter functionality will work with this example. In this example i have used the "lowercase" Filter.
Transpose a matrix in Python
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()
Negative weights using Dijkstra's Algorithm
you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.
this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]
in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.
Android Reading from an Input stream efficiently
Maybe rather then read 'one line at a time' and join the strings, try 'read all available' so as to avoid the scanning for end of line, and to also avoid string joins.
ie, InputStream.available()
and InputStream.read(byte[] b), int offset, int length)
Difference between object and class in Scala
The object keyword creates a new singleton type, which is like a class that only has a single named instance. If you’re familiar with Java, declaring an object in Scala is a lot like creating a new instance of an anonymous class.
Scala has no equivalent to Java’s static keyword, and an object is often used in Scala where you might use a class with static members in Java.
"UnboundLocalError: local variable referenced before assignment" after an if statement
Contributing to ferrix example,
class Battery():
def __init__(self, battery_size = 60):
self.battery_size = battery_size
def get_range(self):
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 270
message = "This car can go approx " + str(range)
message += "Fully charge"
print(message)
My message will not execute, because none of my conditions are fulfill therefore receiving " UnboundLocalError: local variable 'range' referenced before assignment"
def get_range(self):
if self.battery_size <= 70:
range = 240
elif self.battery_size >= 85:
range = 270
Append lines to a file using a StreamWriter
One more simple way is using the File.AppendText
it appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist and returns a System.IO.StreamWriter
using (System.IO.StreamWriter sw = System.IO.File.AppendText(logFilePath + "log.txt"))
{
sw.WriteLine("this is a log");
}
Session timeout in ASP.NET
if you are want session timeout for website than remove
<authentication mode="Forms">
<forms timeout="50"/>
</authentication>
tag from web.config file.
How to remove carriage returns and new lines in Postgresql?
In the case you need to remove line breaks from the begin or end of the string, you may use this:
UPDATE table
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );
Have in mind that the hat ^
means the begin of the string and the dollar sign $
means the end of the string.
Hope it help someone.
Call a stored procedure with parameter in c#
You have to add parameters since it is needed for the SP to execute
using (SqlConnection con = new SqlConnection(dc.Con))
{
using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", txtfirstname.Text);
cmd.Parameters.AddWithValue("@LastName", txtlastname.Text);
con.Open();
cmd.ExecuteNonQuery();
}
}
Using env variable in Spring Boot's application.properties
Maybe I write this too late, but I have gotten the similar problem when I have tried to override methods for reading properties.
My problem have been:
1) Read property from env if this property has been set in env
2) Read property from system property if this property have been setted in system property
3) And last, read from application properties.
So, for resolving this problem I go to my bean configuration class
@Validated
@Configuration
@ConfigurationProperties(prefix = ApplicationConfiguration.PREFIX)
@PropertySource(value = "${application.properties.path}", factory = PropertySourceFactoryCustom.class)
@Data // lombok
public class ApplicationConfiguration {
static final String PREFIX = "application";
@NotBlank
private String keysPath;
@NotBlank
private String publicKeyName;
@NotNull
private Long tokenTimeout;
private Boolean devMode;
public void setKeysPath(String keysPath) {
this.keysPath = StringUtils.cleanPath(keysPath);
}
}
And overwrite factory in @PropertySource. And then I have created my own implementation for reading properties.
public class PropertySourceFactoryCustom implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
return name != null ? new PropertySourceCustom(name, resource) : new PropertySourceCustom(resource);
}
}
And created PropertySourceCustom
public class PropertySourceCustom extends ResourcePropertySource {
public LifeSourcePropertySource(String name, EncodedResource resource) throws IOException {
super(name, resource);
}
public LifeSourcePropertySource(EncodedResource resource) throws IOException {
super(resource);
}
public LifeSourcePropertySource(String name, Resource resource) throws IOException {
super(name, resource);
}
public LifeSourcePropertySource(Resource resource) throws IOException {
super(resource);
}
public LifeSourcePropertySource(String name, String location, ClassLoader classLoader) throws IOException {
super(name, location, classLoader);
}
public LifeSourcePropertySource(String location, ClassLoader classLoader) throws IOException {
super(location, classLoader);
}
public LifeSourcePropertySource(String name, String location) throws IOException {
super(name, location);
}
public LifeSourcePropertySource(String location) throws IOException {
super(location);
}
@Override
public Object getProperty(String name) {
if (StringUtils.isNotBlank(System.getenv(name)))
return System.getenv(name);
if (StringUtils.isNotBlank(System.getProperty(name)))
return System.getProperty(name);
return super.getProperty(name);
}
}
So, this has helped me.
Implement Stack using Two Queues
Here's my answer - where the 'pop' is inefficient.
Seems that all algorithms that come immediately to mind have N complexity, where N is the size of the list: whether you choose to do work on the 'pop' or do work on the 'push'
The algorithm where lists are traded back and fourth may be better,
as a size calculation is not needed, although you still need to loop and compare with empty.
you can prove this algorithm cannot be written faster than N by noting that the information about the last element in a queue is only available through knowing the size of the queue, and that you must destroy data to get to that element, hence the 2nd queue.
The only way to make this faster is to not to use queues in the first place.
from data_structures import queue
class stack(object):
def __init__(self):
q1= queue
q2= queue #only contains one item at most. a temp var. (bad?)
def push(self, item):
q1.enque(item) #just stick it in the first queue.
#Pop is inefficient
def pop(self):
#'spin' the queues until q1 is ready to pop the right value.
for N 0 to self.size-1
q2.enqueue(q1.dequeue)
q1.enqueue(q2.dequeue)
return q1.dequeue()
@property
def size(self):
return q1.size + q2.size
@property
def isempty(self):
if self.size > 0:
return True
else
return False
HTML text-overflow ellipsis detection
All the solutions did not really work for me, what did work was compare the elements scrollWidth
to the scrollWidth
of its parent (or child, depending on which element has the trigger).
When the child's scrollWidth
is higher than its parents, it means .text-ellipsis
is active.
When event
is the parent element
function isEllipsisActive(event) {
let el = event.currentTarget;
let width = el.offsetWidth;
let widthChild = el.firstChild.offsetWidth;
return (widthChild >= width);
}
When event
is the child element
function isEllipsisActive(event) {
let el = event.currentTarget;
let width = el.offsetWidth;
let widthParent = el.parentElement.scrollWidth;
return (width >= widthParent);
}
Git submodule head 'reference is not a tree' error
This error can mean that a commit is missing in the submodule. That is, the repository (A) has a submodule (B). A wants to load B so that it is pointing to a certain commit (in B). If that commit is somehow missing, you'll get that error. Once possible cause: the reference to the commit was pushed in A, but the actual commit was not pushed from B. So I'd start there.
Less likely, there's a permissions problem, and the commit cannot be pulled (possible if you're using git+ssh).
Make sure the submodule paths look ok in .git/config and .gitmodules.
One last thing to try - inside the submodule directory: git reset HEAD --hard
SQL SERVER, SELECT statement with auto generate row id
Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..
Mapping object to dictionary and vice versa
Reflection can take you from an object to a dictionary by iterating over the properties.
To go the other way, you'll have to use a dynamic ExpandoObject (which, in fact, already inherits from IDictionary, and so has done this for you) in C#, unless you can infer the type from the collection of entries in the dictionary somehow.
So, if you're in .NET 4.0 land, use an ExpandoObject, otherwise you've got a lot of work to do...
How do I show my global Git configuration?
You can use:
git config --list
or look at your ~/.gitconfig
file. The local configuration will be in your repository's .git/config
file.
Use:
git config --list --show-origin
to see where that setting is defined (global, user, repo, etc...)
Insert images to XML file
The most common way of doing this is to include the binary as base-64 in an element. However, this is a workaround, and adds a bit of volume to the file.
For example, this is the bytes 00 to 09 (note we needed 16 bytes to encode 10 bytes worth of data):
<xml><image>AAECAwQFBgcICQ==</image></xml>
how you do this encoding varies per architecture. For example, with .NET you might use Convert.ToBase64String
, or XmlWriter.WriteBase64
.
Ruby: How to convert a string to boolean
In a rails 5.1 app, I use this core extension built on top of ActiveRecord::Type::Boolean
. It is working perfectly for me when I deserialize boolean from JSON string.
https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html
# app/lib/core_extensions/string.rb
module CoreExtensions
module String
def to_bool
ActiveRecord::Type::Boolean.new.deserialize(downcase.strip)
end
end
end
initialize core extensions
# config/initializers/core_extensions.rb
String.include CoreExtensions::String
rspec
# spec/lib/core_extensions/string_spec.rb
describe CoreExtensions::String do
describe "#to_bool" do
%w[0 f F false FALSE False off OFF Off].each do |falsey_string|
it "converts #{falsey_string} to false" do
expect(falsey_string.to_bool).to eq(false)
end
end
end
end
Jquery array.push() not working
another workaround:
var myarray = [];
$("#test").click(function() {
myarray[index]=$("#drop").val();
alert(myarray);
});
i wanted to add all checked checkbox to array. so example, if .each is used:
var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
if (this.checked) {
var p=$('.pp').eq(idx).val();
vpp[incr]=(p);
incr++;
}
});
//do what ever with vpp array;
How do I discard unstaged changes in Git?
You can use git stash - if something goes wrong, you can still revert from the stash.
Similar to some other answer here, but this one also removes all unstaged files and also all unstaged deletes:
git add .
git stash
if you check that everything is OK, throw the stash away:
git stash drop
The answer from Bilal Maqsood with git clean
also worked for me, but with the stash I have more control - if I do sth accidentally, I can still get my changes back
UPDATE
I think there is 1 more change (don't know why this worked for me before):
git add . -A
instead of git add .
without the -A
the removed files will not be staged
How to compute the similarity between two text documents?
I am combining the solutions from answers of @FredFoo and @Renaud. My solution is able to apply @Renaud's preprocessing on the text corpus of @FredFoo and then display pairwise similarities where the similarity is greater than 0. I ran this code on Windows by installing python and pip first. pip is installed as part of python but you may have to explicitly do it by re-running the installation package, choosing modify and then choosing pip. I use the command line to execute my python code saved in a file "similarity.py". I had to execute the following commands:
>set PYTHONPATH=%PYTHONPATH%;C:\_location_of_python_lib_
>python -m pip install sklearn
>python -m pip install nltk
>py similarity.py
The code for similarity.py is as follows:
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk, string
import numpy as np
nltk.download('punkt') # if necessary...
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item) for item in tokens]
def normalize(text):
return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
corpus = ["I'd like an apple",
"An apple a day keeps the doctor away",
"Never compare an apple to an orange",
"I prefer scikit-learn to Orange",
"The scikit-learn docs are Orange and Blue"]
vect = TfidfVectorizer(tokenizer=normalize, stop_words='english')
tfidf = vect.fit_transform(corpus)
pairwise_similarity = tfidf * tfidf.T
#view the pairwise similarities
print(pairwise_similarity)
#check how a string is normalized
print(normalize("The scikit-learn docs are Orange and Blue"))
How can I force a long string without any blank to be wrapped?
I don't think you can do this with CSS. Instead, at regular 'word lengths' along the string, insert an HTML soft-hyphen:
ACTGATCG­AGCTGAAG­CGCAGTGC­GATGCTTC­GATGATGC­TGACGATG
This will display a hyphen at the end of the line, where it wraps, which may or may not be what you want.
Note Safari seems to wrap the long string in a <textarea>
anyway, unlike Firefox.
How to compile a static library in Linux?
Here a full makefile example:
makefile
TARGET = prog
$(TARGET): main.o lib.a
gcc $^ -o $@
main.o: main.c
gcc -c $< -o $@
lib.a: lib1.o lib2.o
ar rcs $@ $^
lib1.o: lib1.c lib1.h
gcc -c -o $@ $<
lib2.o: lib2.c lib2.h
gcc -c -o $@ $<
clean:
rm -f *.o *.a $(TARGET)
explaining the makefile:
target: prerequisites
- the rule head
$@
- means the target
$^
- means all prerequisites
$<
- means just the first prerequisite
ar
- a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
r
- replace files existing inside the archive
c
- create a archive if not already existent
s
- create an object-file index into the archive
To conclude: The static library under Linux is nothing more than a archive of object files.
main.c using the lib
#include <stdio.h>
#include "lib.h"
int main ( void )
{
fun1(10);
fun2(10);
return 0;
}
lib.h the libs main header
#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED
#include "lib1.h"
#include "lib2.h"
#endif
lib1.c first lib source
#include "lib1.h"
#include <stdio.h>
void fun1 ( int x )
{
printf("%i\n",x);
}
lib1.h the corresponding header
#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED
#ifdef __cplusplus
extern “C” {
#endif
void fun1 ( int x );
#ifdef __cplusplus
}
#endif
#endif /* LIB1_H_INCLUDED */
lib2.c second lib source
#include "lib2.h"
#include <stdio.h>
void fun2 ( int x )
{
printf("%i\n",2*x);
}
lib2.h the corresponding header
#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED
#ifdef __cplusplus
extern “C” {
#endif
void fun2 ( int x );
#ifdef __cplusplus
}
#endif
#endif /* LIB2_H_INCLUDED */
How to atomically delete keys matching a pattern using Redis
You can also use this command to delete the keys:-
Suppose there are many types of keys in your redis like-
- 'xyz_category_fpc_12'
- 'xyz_category_fpc_245'
- 'xyz_category_fpc_321'
- 'xyz_product_fpc_876'
- 'xyz_product_fpc_302'
- 'xyz_product_fpc_01232'
Ex- 'xyz_category_fpc' here xyz is a sitename, and these keys are related to products and categories of a E-Commerce site and generated by FPC.
If you use this command as below-
redis-cli --scan --pattern 'key*' | xargs redis-cli del
OR
redis-cli --scan --pattern 'xyz_category_fpc*' | xargs redis-cli del
It deletes all the keys like 'xyz_category_fpc' (delete 1, 2 and 3 keys). For delete other 4, 5 and 6 number keys use 'xyz_product_fpc' in above command.
If you want to Delete Everything in Redis, then follow these Commands-
With redis-cli:
- FLUSHDB - Removes data from your connection's CURRENT database.
- FLUSHALL - Removes data from ALL databases.
For Example:- in your shell:
redis-cli flushall
redis-cli flushdb
Most efficient way to find mode in numpy array
I think a very simple way would be to use the Counter class. You can then use the most_common() function of the Counter instance as mentioned here.
For 1-d arrays:
import numpy as np
from collections import Counter
nparr = np.arange(10)
nparr[2] = 6
nparr[3] = 6 #6 is now the mode
mode = Counter(nparr).most_common(1)
# mode will be [(6,3)] to give the count of the most occurring value, so ->
print(mode[0][0])
For multiple dimensional arrays (little difference):
import numpy as np
from collections import Counter
nparr = np.arange(10)
nparr[2] = 6
nparr[3] = 6
nparr = nparr.reshape((10,2,5)) #same thing but we add this to reshape into ndarray
mode = Counter(nparr.flatten()).most_common(1) # just use .flatten() method
# mode will be [(6,3)] to give the count of the most occurring value, so ->
print(mode[0][0])
This may or may not be an efficient implementation, but it is convenient.