In case you are trying to use xclip on remote host just add -X to your ssh command
ssh user@host -X
More detailed information can be found here : https://askubuntu.com/a/305681
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
No one mentions anything about the --single-transaction option. People should use it by default for InnoDB tables to ensure data consistency. In this case:
mysqldump --single-transaction -h [remoteserver.com] -u [username] -p [password] [yourdatabase] > [dump_file.sql]
This makes sure the dump is run in a single transaction that's isolated from the others, preventing backup of a partial transaction.
For instance, consider you have a game server where people can purchase gears with their account credits. There are essentially 2 operations against the database:
Now if the dump happens in between these operations, the next time you restore the backup would result in the user losing the purchased item, because the second operation isn't dumped in the SQL dump file.
While it's just an option, there are basically not much of a reason why you don't use this option with mysqldump.
hey there for anyone who might be looking for solution like this.. i had issue with scaling inside WebView so best way to do is in your java.class where you set all for webView put this two line of code: (webViewSearch is name of my webView -->webViewSearch = (WebView) findViewById(R.id.id_webview_search);)
// force WebView to show content not zoomed---------------------------------------------------------
webViewSearch.getSettings().setLoadWithOverviewMode(true);
webViewSearch.getSettings().setUseWideViewPort(true);
window.WindowStyle = WindowStyle.None;
window.ResizeMode = ResizeMode.NoResize;
window.Left = 0;
window.Top = 0;
window.Width = SystemParameters.VirtualScreenWidth;
window.Height = SystemParameters.VirtualScreenHeight;
window.Topmost = true;
Works with multiple screens
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxy.somewhere.com</host>
<port>8080</port>
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
</proxy>
</proxies>
</settings>
Window > Preferences > Maven > User Settings
Sounds like you're expecting size_t
to be the same as unsigned long
(possibly 64 bits) when it's actually an unsigned int
(32 bits). Try using %zu
in both cases.
I'm not entirely certain though.
size_t should be defined in your standard library's headers. In my experience, it usually is simply a typedef to unsigned int. The point, though, is that it doesn't have to be. Types like size_t allow the standard library vendor the freedom to change its underlying data types if appropriate for the platform. If you assume size_t is always unsigned int (via casting, etc), you could run into problems in the future if your vendor changes size_t to be e.g. a 64-bit type. It is dangerous to assume anything about this or any other library type for this reason.
You shouldn't use the double-bracket {{ }}
syntax within if
or ifequal
statements, you can simply access the variable there like you would in normal python:
{% if title == source %}
...
{% endif %}
You can do forward typedef. But to do
typedef A B;
you must first forward declare A
:
class A;
typedef A B;
This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.
It is also good idea to use supervisord or runit[1] for service management.
Removing the below from the ~/.gitattributes file
* text=auto
will prevent git from checking line-endings in the first-place.
This solution for Ubuntu Host, Macos Guest
Disabling SIP
Finally, disable HiDPI:
$ sudo defaults write /Library/Preferences/com.apple.windowserver DisplayResolutionEnabled -bool NO
For AMD processors:
You don't need Genymotion, just create a new Virtual Device and while selecting the system Image select the ABI as armeabi instead of the default x86 one.
If you run VMware Player or Workstation (or maybe VirtualBox, I'm not sure if it supports Mac OS X, but may), and then Mac OS X Server (Client can't legally be virtualized). Of course, in this case you are running XCode on OS X, but your host machine could be linux.
If your database is straightforward and simple, LINQ to SQL will do. If you need logical/abstracted entities on top of your tables, then go for Entity Framework.
You can also use,
parent.jQuery("#testdiv").attr("style", content from form);
Seems reflection only help here.. I've done small example of converting object to dictionary and vise versa:
[TestMethod]
public void DictionaryTest()
{
var item = new SomeCLass { Id = "1", Name = "name1" };
IDictionary<string, object> dict = ObjectToDictionary<SomeCLass>(item);
var obj = ObjectFromDictionary<SomeCLass>(dict);
}
private T ObjectFromDictionary<T>(IDictionary<string, object> dict)
where T : class
{
Type type = typeof(T);
T result = (T)Activator.CreateInstance(type);
foreach (var item in dict)
{
type.GetProperty(item.Key).SetValue(result, item.Value, null);
}
return result;
}
private IDictionary<string, object> ObjectToDictionary<T>(T item)
where T: class
{
Type myObjectType = item.GetType();
IDictionary<string, object> dict = new Dictionary<string, object>();
var indexer = new object[0];
PropertyInfo[] properties = myObjectType.GetProperties();
foreach (var info in properties)
{
var value = info.GetValue(item, indexer);
dict.Add(info.Name, value);
}
return dict;
}
What you can utilize is some sort of templating engine like pug (formerly jade). To enable it you should do the following:
npm install --save pug
- to add it to the project and package.json fileapp.set('view engine', 'pug');
- register it as a view engine in express./views
folder and add a simple .pug
file like so:html
head
title= title
body
h1= message
note that the spacing is very important!
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
This will render an index.html page with the variables passed in node.js changed to the values you have provided. This has been taken directly from the expressjs templating engine page: http://expressjs.com/en/guide/using-template-engines.html
For more info on pug you can also check: https://github.com/pugjs/pug
create trigger doct_trigger
after delete on doctor
for each row
delete from patient where patient.PrimaryDoctor_SSN=doctor.SSN ;
Since Entity Framework 5.0 you can use following code in order to solve your issue:
public abstract class YourContext : DbContext
{
public YourContext()
{
(this as IObjectContextAdapter).ObjectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;
}
}
This should solve your problems as Entity Framerwork will use 'C# like' null comparison.
PendingIntent
is basically an object that wraps another Intent
object. Then it can be passed to a foreign application where you’re granting that app the right to perform the operation, i.e., execute the intent as if it were executed from your own app’s process (same permission and identity). For security reasons you should always pass explicit intents to a PendingIntent rather than being implicit.
PendingIntent aPendingIntent = PendingIntent.getService(Context, 0, aIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
You need to declare the Builder
inner class as static
.
Consult some documentation for both non-static inner classes and static inner classes.
Basically the non-static inner classes instances cannot exist without attached outer class instance.
Use --build-arg in lower case environment variable:
docker build --build-arg http_proxy=http://proxy:port/ --build-arg https_proxy=http://proxy:port/ --build-arg ftp_proxy=http://proxy:port --build-arg no_proxy=localhost,127.0.0.1,company.com -q=false .
Note: localhost
is the hostname for an address using the local (loopback) network interface, and 127.0.0.1
is its IP in the IPv4 network standard (it's ::1
in IPv6). 0.0.0.0
is the IPv4 standard "current network" IP address.
I experienced this error with a Docker setup. I had a Docker container running on an external server, and I'd (correctly) mapped its ports out as 127.0.0.1:9232:9232
. By port-forwarding ssh remote -L 9232:127.0.0.1:9232
, I'd expected to be able to communicate with the remote
server's port 9232
as if it were my own local port.
It turned out that the Docker container was internally running its process on 127.0.0.1:9232
rather than 0.0.0.0:9232
, and so even though I'd specified the container's port-mappings correctly, they weren't on the correct interface for being mapped out.
Simply install rxjs-compat to solve the problem
npm i rxjs-compat --save-dev
And import it like below
import 'rxjs/Rx';
This is sort of an indirect approach, but you could see if a website loads on your web browser of choice from whatever is running on port 80. Or you could telnet to port 80 and see if you get a response that gives you a clue as to what is running on that port and you can go shut it down. Since port 80 is the default port for http traffic chances are there is some sort of http server running there by default, but there's no guarantee.
Update: As of November, 2020, Gitlens appears within VSCode's builtin Source Control Panel
I would recommend to use: Git Lens.
This should work (where enquiryId
is the id you need to match against):
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == enquiryId);
What this does is passes each vehicle in the list into the lambda predicate, evaluating the predicate. If the predicate returns true (ie. vehicle.EnquiryID == enquiryId
), then the current vehicle will be removed from the list.
If you know the types of the objects in your collections, then using the generic collections is a better approach. It avoids casting when retrieving objects from the collections, but can also avoid boxing if the items in the collection are value types (which can cause performance issues).
To add on:
you can insert a time check within a loop with intensive or possible deadlock, ie.
:
section_toc_conditionalBreakOff;
:
where within this section
if (toc > timeRequiredToBreakOff) % time conditional break off
return;
% other options may be:
% 1. display intermediate values with pause;
% 2. exit; % in some cases, extreme : kill/ quit matlab
end
The really quick and dirty way is to point to a local file:
<dependency>
<groupId>sample</groupId>
<artifactId>com.sample</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>C:\DEV\myfunnylib\yourJar.jar</systemPath>
</dependency>
However this will only live on your machine (obviously), for sharing it usually makes sense to use a proper m2 archive (nexus/artifactory) or if you do not have any of these or don't want to set one up a local maven structured archive and configure a "repository" in your pom: local:
<repositories>
<repository>
<id>my-local-repo</id>
<url>file://C:/DEV//mymvnrepo</url>
</repository>
</repositories>
remote:
<repositories>
<repository>
<id>my-remote-repo</id>
<url>http://192.168.0.1/whatever/mavenserver/youwant/repo</url>
</repository>
</repositories>
for this a relative path is also possible using the basedir variable:
<url>file:${basedir}</url>
var BlobBuilder = (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder);
can be used without the try catch.
Thankx to check_ca. Great work.
Better way to reset your form with jQuery is Simply trigger
a reset
event on your form.
$("#btn1").click(function () {
$("form").trigger("reset");
});
datascroller was created in part to solve this problem.
pip install datascroller
It loads the dataframe into a terminal view you can "scroll" with your mouse or arrow keys, kind of like an Excel workbook at the terminal that supports querying, highlighting, etc.
import pandas as pd
from datascroller import scroll
# Call `scroll` with a Pandas DataFrame as the sole argument:
my_df = pd.read_csv('<path to your csv>')
scroll(my_df)
I also had trouble overruling a dependency in a third party library. I used scot's approach with the exclusion but I also added the dependency with the newer version in the pom. (I used Maven 3.3.3)
So for the stAX example it would look like this:
<dependency>
<groupId>a.group</groupId>
<artifactId>a.artifact</artifactId>
<version>a.version</version>
<exclusions>
<!-- STAX comes with Java 1.6 -->
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>javax.xml.stream</groupId>
</exclusion>
<exclusion>
<artifactId>stax-api</artifactId>
<groupId>stax</groupId>
</exclusion>
</exclusions>
<dependency>
<dependency>
<groupId>javax.xml.stream</groupId>
<artifactId>stax-api</artifactId>
<version>1.0-2</version>
</dependency>
That will only work for small numbers and I'm guessing it's also implementation-dependent. Python uses the same object instance for small numbers (iirc <256), but this changes for bigger numbers.
>>> a = 2104214124
>>> b = 2104214124
>>> a == b
True
>>> a is b
False
So you should always use ==
to compare numbers.
Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call
.
#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])
If you want to do things while it is executing or feed things into stdin
, you can use communicate
after the popen
call.
#start and process things, then wait
p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"])
print "Happens while running"
p.communicate() #now wait plus that you can send commands to process
As stated in the documentation, wait
can deadlock, so communicate is advisable.
Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven
. And I say our because I'm just getting introduced to maven
.
In Eclipse
, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:
dependency
statement into your pom.xml
mvn
Now, maven
will connect and download the jar
along with the list of dependencies, and automatically resolve any additional dependencies that jar
may have had. So if the jar
also needed commons-logging, that will be downloaded as well.
You need to add the attribute "formnovalidate" to the control that is triggering the browser validation, e.g.:
<input type="image" id="fblogin" formnovalidate src="/images/facebook_connect.png">
'ASP.net MessageBox
'Add a scriptmanager to the ASP.Net Page
<asp:scriptmanager id="ScriptManager1" runat="server" />
try:
{
string sMsg = "My Message";
ScriptManager.RegisterStartupScript(Page, Page.GetType, Guid.NewGuid().ToString(), "alert('" + sMsg + "')", true);
}
import (
"bufio"
"os"
)
var (
reader = bufio.NewReader(os.Stdin)
)
func ReadFromStdin() string{
result, _ := reader.ReadString('\n')
witl := result[:len(result)-1]
return witl
}
Here is an example with function ReadFromStdin()
it's like fmt.Scan(&name)
but its takes all strings with blank spaces like: "Hello My Name Is ..."
var name string = ReadFromStdin()
println(name)
If you tried to "make install" in your project directory with this error you can try it:
rm -rf ./node_modules
npm cache clear
npm remove sails
then you can try to "make install"
If you have the "npm ERR! enoent ENOENT: no such file or directory, chmod '.../djam-backend/node_modules/js-beautify/js/bin/css-beautify.js'" then you can try to install some previous version of the js-beautify, more comments: https://github.com/beautify-web/js-beautify/issues/1247
"dependencies": {
...
"js-beautify": "1.6.14"
...
}
and the run "make install". It seem works in case if you have not other dependencies that requires higher version (1.7.0) in this case you must downgrade this packages also in the packages.json.
or
Starting eclipse with eclipse -clean did wonders for me.
ng-if="select.name.indexOf('?') !== -1"
You could use jquery ui's switchClass
, Heres an example:
$( "selector" ).switchClass( "oldClass", "newClass", 1000, "easeInOutQuad" );
Or see this jsfiddle.
Background location service. It will be restarted even after killing the app.
MainActivity.java
public class MainActivity extends AppCompatActivity {
AlarmManager alarmManager;
Button stop;
PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (alarmManager == null) {
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceive.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000,
pendingIntent);
}
}
}
BookingTrackingService.java
public class BookingTrackingService extends Service implements LocationListener {
private static final String TAG = "BookingTrackingService";
private Context context;
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude, longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 30000;
public double track_lat = 0.0;
public double track_lng = 0.0;
public static String str_receiver = "servicetutorial.service.receiver";
Intent intent;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
intent = new Intent(str_receiver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.context = this;
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy <<");
if (mTimer != null) {
mTimer.cancel();
}
}
private void trackLocation() {
Log.e(TAG, "trackLocation");
String TAG_TRACK_LOCATION = "trackLocation";
Map<String, String> params = new HashMap<>();
params.put("latitude", "" + track_lat);
params.put("longitude", "" + track_lng);
Log.e(TAG, "param_track_location >> " + params.toString());
stopSelf();
mTimer.cancel();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
/******************************/
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable) {
Log.e(TAG, "CAN'T GET LOCATION");
stopSelf();
} else {
if (isNetworkEnable) {
location = null;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.e(TAG, "isNetworkEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
track_lat = latitude;
track_lng = longitude;
// fn_update(location);
}
}
}
if (isGPSEnable) {
location = null;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e(TAG, "isGPSEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
track_lat = latitude;
track_lng = longitude;
// fn_update(location);
}
}
}
Log.e(TAG, "START SERVICE");
trackLocation();
}
}
private class TimerTaskToGetLocation extends TimerTask {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
fn_getlocation();
}
});
}
}
// private void fn_update(Location location) {
//
// intent.putExtra("latutide", location.getLatitude() + "");
// intent.putExtra("longitude", location.getLongitude() + "");
// sendBroadcast(intent);
// }
}
AlarmReceive.java (BroadcastReceiver)
public class AlarmReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("Service_call_" , "You are in AlarmReceive class.");
Intent background = new Intent(context, BookingTrackingService.class);
// Intent background = new Intent(context, GoogleService.class);
Log.e("AlarmReceive ","testing called broadcast called");
context.startService(background);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<service
android:name=".ServiceAndBroadcast.BookingTrackingService"
android:enabled="true" />
<receiver
android:name=".ServiceAndBroadcast.AlarmReceive"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
This is a Scala version that is clean and fast (no stackoverflow):
import scala.annotation.tailrec
import java.io._
implicit class InputStreamOps(in: InputStream) {
def >(out: OutputStream): Unit = pipeTo(out)
def pipeTo(out: OutputStream, bufferSize: Int = 1<<10): Unit = pipeTo(out, Array.ofDim[Byte](bufferSize))
@tailrec final def pipeTo(out: OutputStream, buffer: Array[Byte]): Unit = in.read(buffer) match {
case n if n > 0 =>
out.write(buffer, 0, n)
pipeTo(out, buffer)
case _ =>
in.close()
out.close()
}
}
This enables to use >
symbol e.g. inputstream > outputstream
and also pass in custom buffers/sizes.
var dir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
I jumped in for the top rated answer and found myself not getting what I expected. I had to read the comments to find what I was looking for.
For that reason I am posting the answer listed in the comments to give it the exposure it deserves.
You do not need regular expressions to check if a substring exists in a string.
line = 'This,is,a,sample,string'
result = bool('sample' in line) # returns True
If you want to know if a string contains a pattern then you should use re.search
line = 'This,is,a,sample,string'
result = re.search(r'sample', line) # finds 'sample'
This is best used with pattern matching, for example:
line = 'my name is bob'
result = re.search(r'my name is (\S+)', line) # finds 'bob'
^(?!my)\w+$
should work.
It first ensures that it's not possible to match my
at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like ^\s*(?!my)(\w+)\s*$
. In this case, backreference 1 will contain the name of the variable.
And if you need to ensure that your variable name starts with a certain group of characters, say [A-Za-z_]
, use
^(?!my)[A-Za-z_]\w*$
Note the change from +
to *
.
This can be done in one simple line.
Swift 5
var my2DArray = (0..<4).map { _ in Array(0..<) }
You could also map it to instances of any class or struct of your choice
struct MyStructCouldBeAClass {
var x: Int
var y: Int
}
var my2DArray: [[MyStructCouldBeAClass]] = (0..<2).map { x in
Array(0..<2).map { MyStructCouldBeAClass(x: x, y: $0)}
}
Will it warn you if you pass a 32-bit unsigned integer to a %lu format? It should be fine since the conversion is well-defined and doesn't lose any information.
I've heard that some platforms define macros in <inttypes.h>
that you can insert into the format string literal but I don't see that header on my Windows C++ compiler, which implies it may not be cross-platform.
You can also do:
Integer a = '1182-2'.split('-')[0] as Integer
Integer b = '1182-2'.split('-')[1] as Integer
//a=1182 b=2
So, you need to
In my case I had a swift file I wanted to unit test, and the unit test file was also a swift class. I made sure the access modifiers were correct, but the statement
import stMobile
(let's say that stMobile is our target name)
still did not work (I was still getting the 'No such module' error), I checked my target, and its name was indeed stMobile. So, I went to Build Settings, under packaging, and found the Product Module Name, and for some reason this was called St_Mobile, so I changed my import statement
import St_Mobile
(which is the Product Module Name), and everything worked.
So, to sum up:
Check your Product Module Name and use the import statement below in you unit test class
import myProductModuleName
Make sure your access modifiers are correct (class level and your methods).
Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}
Your call to text()
doesn't output anything because you inverted your x and your y:
plot(abs_losses, percent_losses,
main= "Absolute Losses vs. Relative Losses(in%)",
xlab= "Losses (absolute, in miles of millions)",
ylab= "Losses relative (in % of January´2007 value)",
col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)
text(abs_losses, percent_losses, labels=namebank, cex= 0.7)
Now if you want to move your labels down, left, up or right you can add argument pos=
with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)
You can of course gives a vector of value to pos
if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):
pos_vector <- rep(3, length(namebank))
pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)
Your code is correct. Just test to ensure it is being called like:
<script>
function doIt(){
alert("here i am!");
__doPostBack('ctl00$ctl00$bLogout','')
}
</script>
<iframe onload="doIt()"></iframe>
Another method is by using the menu within visual studio. Project -> Add Reference... I recommend copying the needed .dll to your resource folder, or local project folder.
If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));
For linux Ubuntu Open Terminal and Write :-
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
With <button>
, you can use img tags, etc. where text is
<button type='submit'> text -- can be img etc. </button>
with <input>
type, you are limited to text
Class where we override finalize method
public class TestClass {
public TestClass() {
System.out.println("constructor");
}
public void display() {
System.out.println("display");
}
@Override
public void finalize() {
System.out.println("destructor");
}
}
The chances of finalize method being called
public class TestGarbageCollection {
public static void main(String[] args) {
while (true) {
TestClass s = new TestClass();
s.display();
System.gc();
}
}
}
when the memory is overloaded with dump objects the gc will call finalize method
run and see the console, where you dont find the finalize method being called frequently, when the memory is getting overloaded then the finalize method will be called.
You can use the dynamic object ViewBag
to pass data from Controllers to Views.
Add the following to your controller:
ViewBag.MyList = myList;
Then you can acces it from your view:
@ViewBag.MyList
// e.g.
@foreach (var item in ViewBag.MyList) { ... }
Here's the version like the ggplot2 one I gave only in base R. I copied some from @nullglob.
generate the data
carrots <- rnorm(100000,5,2)
cukes <- rnorm(50000,7,2.5)
You don't need to put it into a data frame like with ggplot2. The drawback of this method is that you have to write out a lot more of the details of the plot. The advantage is that you have control over more details of the plot.
## calculate the density - don't plot yet
densCarrot <- density(carrots)
densCuke <- density(cukes)
## calculate the range of the graph
xlim <- range(densCuke$x,densCarrot$x)
ylim <- range(0,densCuke$y, densCarrot$y)
#pick the colours
carrotCol <- rgb(1,0,0,0.2)
cukeCol <- rgb(0,0,1,0.2)
## plot the carrots and set up most of the plot parameters
plot(densCarrot, xlim = xlim, ylim = ylim, xlab = 'Lengths',
main = 'Distribution of carrots and cucumbers',
panel.first = grid())
#put our density plots in
polygon(densCarrot, density = -1, col = carrotCol)
polygon(densCuke, density = -1, col = cukeCol)
## add a legend in the corner
legend('topleft',c('Carrots','Cucumbers'),
fill = c(carrotCol, cukeCol), bty = 'n',
border = NA)
Edit: Use printf("val = 0x%" PRIx64 "\n", val);
instead.
Try printf("val = 0x%llx\n", val);
. See the printf manpage:
ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.
Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t
is not always a unsigned long long
: PRIx64
see also this stackoverflow answer
you can create a function. Add maxdepth as you like for traversing subdirectories.
def findNremove(path,pattern,maxdepth=1):
cpath=path.count(os.sep)
for r,d,f in os.walk(path):
if r.count(os.sep) - cpath <maxdepth:
for files in f:
if files.endswith(pattern):
try:
print "Removing %s" % (os.path.join(r,files))
#os.remove(os.path.join(r,files))
except Exception,e:
print e
else:
print "%s removed" % (os.path.join(r,files))
path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")
Here is a table that is not a SELECT * FROM
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist
Got this from a database pro, here is what I was told:
select 1 from `tablename`; //avoids a function call
select * from INFORMATION_SCHEMA.tables where schema = 'db' and table = 'table' // slow. Field names not accurate
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = does not exist
If you are in Mac OS, you need to open the /usr/local/etc/rabbitmq/rabbitmq-env.conf
and
set NODE_IP_ADDRESS=
, it used to be 127.0.0.1. Then add another user as the accepted answer suggested.
After that, restart rabbitMQ, brew services restart rabbitmq
According to documentation:
random.sample(population, k)
Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Basically, it picks k unique random elements, a sample, from a sequence:
>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]
random.sample
works also directly from a range:
>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]
In addition to sequences, random.sample
works with sets too:
>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]
However, random.sample
doesn't work with arbitrary iterators:
>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set. For dicts, use list(d).
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
ANSWER?
I'm using it for an animation for adding items to a cart - a cart icon floats to the cart area from the product "add" button, when clicked:
function addCartItem(opts) {
for (var i=0; i<opts.qty; i++) {
setTimeout(function() {
console.log('ADDED ONE!');
}, 1000*i);
}
};
NOTE the duration is in unit times n epocs.
So starting at the the click moment, the animations start epoc (of EACH animation) is the product of each one-second-unit multiplied by the number of items.
epoc: https://en.wikipedia.org/wiki/Epoch_(reference_date)
Hope this helps!
I had a similar error & this is what I found.
My environment details were as below: steps followed at my end
c:\>pip --version
pip 20.0.2 from c:\python37_64\lib\site-packages\pip (python 3.7)
C:\>python --version
Python 3.7.6
As per the documentation, apparently, python 3.7 already has the pickle package. So it does not require any additional download. I checked with the following command to make sure & it worked.
C:\Python\Experiements>python
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>>
So, pip install pickle
not required for python v3.7 for sure
You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:
SELECT @NewIdOutputParam = SCOPE_IDENTITY()
Then in test1, retrieve it like so:
DECLARE @NewId INTEGER
EXECUTE test2 @NewId OUTPUT
-- Now use @NewId as needed
As others have pointed out, you are modifying a collection that you are iterating over and that's what's causing the error. The offending code is below:
foreach (KeyValuePair<int, int> kvp in rankings)
{
.....
if((double)(similarModules/modules.Count)>0.6)
{
rankings[kvp.Key] = rankings[kvp.Key] + 4; // <--- This line is the problem
}
.....
What may not be obvious from the code above is where the Enumerator
comes from. In a blog post from a few years back about Eric Lippert provides an example of what a foreach
loop gets expanded to by the compiler. The generated code will look something like:
{
IEnumerator<int> e = ((IEnumerable<int>)values).GetEnumerator(); // <-- This
// is where the Enumerator
// comes from.
try
{
int m; // OUTSIDE THE ACTUAL LOOP in C# 4 and before, inside the loop in 5
while(e.MoveNext())
{
// loop code goes here
}
}
finally
{
if (e != null) ((IDisposable)e).Dispose();
}
}
If you look up the MSDN documentation for IEnumerable (which is what GetEnumerator()
returns) you will see:
Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
Which brings us back to what the error message states and the other answers re-state, you're modifying the underlying collection.
If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->
$searchResultQuery = Users::query();
$searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
$searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null
Or with scope in model :
public function scopeNotNullOnly($query){
return $query->where('status_message', '<>', '');
}
Tools-> Android -> Android Device Monitor
will open a separate window
No, the underscore is the only continuation character. Personally I prefer the occasional use of a continuation character to being forced to use it always as in C#, but apart from the comments issue (which I'd agree is sometimes annoying), getting things to line up is not an issue.
With VS2008 at any rate, just select the second and following lines, hit the tab key several times, and it moves the whole lot across.
If it goes a tiny bit too far, you can delete the excess space a character at a time. It's a little fiddly, but it stays put once it's saved.
On the rare cases where this isn't good enough, I sometimes use the following technique to get it all to line up:
dim results as String = ""
results += "from a in articles "
results += "where a.articleID = 4 " 'and now you can add comments
results += "select a.articleName"
It's not perfect, and I know those that prefer C# will be tut-tutting, but there it is. It's a style choice, but I still prefer it to endless semi-colons.
Now I'm just waiting for someone to tell me I should have used a StringBuilder ;-)
You'll have to find the index of the person
in your persons
array, then use the array's splice
method:
$scope.persons.splice( $scope.persons.indexOf(person), 1 );
django.setup() in the top will not work while you are running a script explicitly. My problem solved when I added this in the bottom of the settings file
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
import sys
if BASE_DIR not in sys.path:
sys.path.append(BASE_DIR)
os.environ['DJANGO_SETTINGS_MODULE'] = "igp_lrpe.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "igp_lrpe.settings")
import django
django.setup()
Updated code
$('a','div.res').click(function(){
var currentAnchor = $(this);
alert(currentAnchor.text());
alert(currentAnchor.attr('href'));
});
You can do the same in Razor or in the Controller, like so..
@{
//do this on the top most of your View, immediately after `using` statement
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}
Or in the Controller..
public ActionResult Receipt() {
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
return View();
}
I tried this in Chrome and IE9, both is downloading the pdf file.
I probably should add I am using RazorPDF to generate my PDFs. Here is a blog about it: http://nyveldt.com/blog/post/Introducing-RazorPDF
If by "given enough time" you mean 100 years and you're creating them at a rate of a billion a second, then yes, you have a 50% chance of having a collision after 100 years.
Execution is top-down. First come, first served.
If execution sequence is important, combine them.
I think this will help you: https://datatables.net/release-datatables/extensions/FixedHeader/examples/header_footer.html
In a nutshell, if you know how to create a dataTable, You just need to add this jQuery line to your bottom:
$(document).ready(function() {
var table = $('#example').DataTable();
new $.fn.dataTable.FixedHeader( table, {
bottom: true
} );
} );
bottom: true // is for making the Bottom header fixed as well.
Following could be one of ways:
dataframe = dataframe.sample(frac=1, random_state=42).reset_index(drop=True)
where
frac=1 means all rows of a dataframe
random_state=42 means keeping same order in each execution
reset_index(drop=True) means reinitialize index for randomized dataframe
Try this:
$NameRegex = "chalmw-dm"
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}
This gives me the same error as trying to split the list up and zip it. ValueError: dictionary update sequence element #0 has length 1916; 2 is required
THAT is your actual question.
The answer is that the elements of your list are not what you think they are. If you type myList[0]
you will find that the first element of your list is not a two-tuple, e.g. ('A', 1)
, but rather a 1916-length iterable.
Once you actually have a list in the form you stated in your original question (myList = [('A',1),('B',2),...]
), all you need to do is dict(myList)
.
The proper way of using NSLog, as the warning tries to explain, is the use of a formatter, instead of passing in a literal:
Instead of:
NSString *digit = [[sender titlelabel] text];
NSLog(digit);
Use:
NSString *digit = [[sender titlelabel] text];
NSLog(@"%@",digit);
It will still work doing that first way, but doing it this way will get rid of the warning.
I removed " at the end of the connection string and it worked
Instead of
App=EntityFramework"
Used
App=EntityFramework;
<add name="DefaultConnection" connectionString="data source=(local);initial catalog=NamSdb;persist security info=True;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.SqlClient" />
Note : In connectionString Do not include :
|x| Metadata info : "metadata=res://*/"
|x| Encoded Quotes : """
>>> from dis import dis
>>> dis(compile('not 10 == 20', '', 'exec'))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 1 (20)
6 COMPARE_OP 2 (==)
9 UNARY_NOT
10 POP_TOP
11 LOAD_CONST 2 (None)
14 RETURN_VALUE
>>> dis(compile('10 != 20', '', 'exec'))
1 0 LOAD_CONST 0 (10)
3 LOAD_CONST 1 (20)
6 COMPARE_OP 3 (!=)
9 POP_TOP
10 LOAD_CONST 2 (None)
13 RETURN_VALUE
Here you can see that not x == y
has one more instruction than x != y
. So the performance difference will be very small in most cases unless you are doing millions of comparisons and even then this will likely not be the cause of a bottleneck.
The use
operator is for giving aliases to names of classes, interfaces or other namespaces. Most use
statements refer to a namespace or class that you'd like to shorten:
use My\Full\Namespace;
is equivalent to:
use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo
If the use
operator is used with a class or interface name, it has the following uses:
// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;
// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;
The use
operator is not to be confused with autoloading. A class is autoloaded (negating the need for include
) by registering an autoloader (e.g. with spl_autoload_register
). You might want to read PSR-4 to see a suitable autoloader implementation.
To make it simple,
To get host name,
hostname
or
uname -n
or
cat /etc/host
Output can be redirected to any file & read back from application
E.g.: # hostname > /usr/src//hostname.txt
Remove your Gemfile.lock.
Move to bash if you are using zsh.
sudo bash
gem update --system
Now run command bundle to create a new Gemfile.lock file.
Move back to your zsh sudo exec zsh
now run your rake commands.
Integer is an wrapper class/Object and int is primitive type. This difference plays huge role when you want to store int values in a collection, because they accept only objects as values (until jdk1.4). JDK5 onwards because of autoboxing it is whole different story.
alert() is a method of the window object that cannot interpret HTML tags
Check out http://www.asciitable.com/
Look at the Hx
, (Hex) column; 2C
maps to ,
Any unusual encoding can be checked this way
+----+-----+----+-----+----+-----+----+-----+
| Hx | Chr | Hx | Chr | Hx | Chr | Hx | Chr |
+----+-----+----+-----+----+-----+----+-----+
| 00 | NUL | 20 | SPC | 40 | @ | 60 | ` |
| 01 | SOH | 21 | ! | 41 | A | 61 | a |
| 02 | STX | 22 | " | 42 | B | 62 | b |
| 03 | ETX | 23 | # | 43 | C | 63 | c |
| 04 | EOT | 24 | $ | 44 | D | 64 | d |
| 05 | ENQ | 25 | % | 45 | E | 65 | e |
| 06 | ACK | 26 | & | 46 | F | 66 | f |
| 07 | BEL | 27 | ' | 47 | G | 67 | g |
| 08 | BS | 28 | ( | 48 | H | 68 | h |
| 09 | TAB | 29 | ) | 49 | I | 69 | i |
| 0A | LF | 2A | * | 4A | J | 6A | j |
| 0B | VT | 2B | + | 4B | K | 6B | k |
| 0C | FF | 2C | , | 4C | L | 6C | l |
| 0D | CR | 2D | - | 4D | M | 6D | m |
| 0E | SO | 2E | . | 4E | N | 6E | n |
| 0F | SI | 2F | / | 4F | O | 6F | o |
| 10 | DLE | 30 | 0 | 50 | P | 70 | p |
| 11 | DC1 | 31 | 1 | 51 | Q | 71 | q |
| 12 | DC2 | 32 | 2 | 52 | R | 72 | r |
| 13 | DC3 | 33 | 3 | 53 | S | 73 | s |
| 14 | DC4 | 34 | 4 | 54 | T | 74 | t |
| 15 | NAK | 35 | 5 | 55 | U | 75 | u |
| 16 | SYN | 36 | 6 | 56 | V | 76 | v |
| 17 | ETB | 37 | 7 | 57 | W | 77 | w |
| 18 | CAN | 38 | 8 | 58 | X | 78 | x |
| 19 | EM | 39 | 9 | 59 | Y | 79 | y |
| 1A | SUB | 3A | : | 5A | Z | 7A | z |
| 1B | ESC | 3B | ; | 5B | [ | 7B | { |
| 1C | FS | 3C | < | 5C | \ | 7C | | |
| 1D | GS | 3D | = | 5D | ] | 7D | } |
| 1E | RS | 3E | > | 5E | ^ | 7E | ~ |
| 1F | US | 3F | ? | 5F | _ | 7F | DEL |
+----+-----+----+-----+----+-----+----+-----+
For me, it was a Windows Service that was installed and running. Once I stopped it, the build was successful.
Here is my summary of the above solutions to concatenate / combine two columns with int and str value into a new column, using a separator between the values of columns. Three solutions work for this purpose.
# be cautious about the separator, some symbols may cause "SyntaxError: EOL while scanning string literal".
# e.g. ";;" as separator would raise the SyntaxError
separator = "&&"
# pd.Series.str.cat() method does not work to concatenate / combine two columns with int value and str value. This would raise "AttributeError: Can only use .cat accessor with a 'category' dtype"
df["period"] = df["Year"].map(str) + separator + df["quarter"]
df["period"] = df[['Year','quarter']].apply(lambda x : '{} && {}'.format(x[0],x[1]), axis=1)
df["period"] = df.apply(lambda x: f'{x["Year"]} && {x["quarter"]}', axis=1)
All what you have to do is to select and download the bootstrap.css and bootstrap.js files from Bootswatch website, and then replace the original files with them.
Of course you have to add the paths to your layout page after the jQuery path that is all.
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This topic is quite old, but here is a handy solution that I found:
http://www.cityinthesky.co.uk/opensource/pdf2svg/
It offers a tool, pdf2png, which once installed does exactly the job in command line. I've tested it with irreproachable results so far, including with bitmaps.
EDIT : My mistake, this tool also converts letters to paths, so it does not address the initial question. However it does a good job anyway, and can be useful to anyone who does not intend to modify the code in the svg file, so I'll leave the post.
I follow this way to append a new line in a .csv file:
pose_x = 1
pose_y = 2
with open('path-to-your-csv-file.csv', mode='a') as file_:
file_.write("{},{}".format(pose_x, pose_y))
file_.write("\n")
strftime
(C89)
Martin mentioned it, here's an example:
main.c
#include <assert.h>
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
printf("%s\n", s);
return 0;
}
Compile and run:
gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Sample output:
Thu Apr 14 22:39:03 2016
The %c
specifier produces the same format as ctime
.
One advantage of this function is that it returns the number of bytes written, allowing for better error control in case the generated string is too long:
RETURN VALUE
Provided that the result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s. If the length of the result string (including the terminating null byte) would exceed max bytes, then
strftime() returns 0, and the contents of the array are undefined.
Note that the return value 0 does not necessarily indicate an error. For example, in many locales %p yields an empty string. An empty format string will likewise yield an empty string.
asctime
and ctime
(C89, deprecated in POSIX 7)
asctime
is a convenient way to format a struct tm
:
main.c
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s", asctime(tm));
return 0;
}
Sample output:
Wed Jun 10 16:10:32 2015
And there is also ctime()
which the standard says is a shortcut for:
asctime(localtime())
As mentioned by Jonathan Leffler, the format has the shortcoming of not having timezone information.
POSIX 7 marked those functions as "obsolescent" so they could be removed in future versions:
The standard developers decided to mark the asctime() and asctime_r() functions obsolescent even though asctime() is in the ISO C standard due to the possibility of buffer overflow. The ISO C standard also provides the strftime() function which can be used to avoid these problems.
C++ version of this question: How to get current time and date in C++?
Tested in Ubuntu 16.04.
>>> k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
>>> k = sorted(k)
>>> k
[[1, 2], [1, 2], [3], [4], [4], [5, 6, 2]]
>>> dedup = [k[i] for i in range(len(k)) if i == 0 or k[i] != k[i-1]]
>>> dedup
[[1, 2], [3], [4], [5, 6, 2]]
I don't know if it's necessarily faster, but you don't have to use to tuples and sets.
For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:
@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
Clearly you're passing in d.keys()
to your shuffle
function. Probably this was written with python2.x (when d.keys()
returned a list). With python3.x, d.keys()
returns a dict_keys
object which behaves a lot more like a set
than a list
. As such, it can't be indexed.
The solution is to pass list(d.keys())
(or simply list(d)
) to shuffle
.
[self.view.layer setBorderColor: [UIColor colorWithRed:0.265 green:0.447 blue:0.767 alpha:1.0f].CGColor];
Yes - different
chmod a+x
will add the exec bits to the file but will not touch other bits. For example file might be still unreadable to others
and group
.
chmod 755
will always make the file with perms 755
no matter what initial permissions were.
This may or may not matter for your script.
I used used fadeIn animation to replace new image for old one
ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();
How about this? Just give it a thought-
import java.util.ArrayList;
class Solution
{
public static void main (String[] args){
ArrayList<String> List_Of_Array = new ArrayList<String>();
List_Of_Array.add("A");
List_Of_Array.add("B");
List_Of_Array.add("C");
List_Of_Array.add("D");
List_Of_Array.add("E");
List_Of_Array.add("F");
List_Of_Array.add("G");
List_Of_Array.add("H");
int i[] = {1,3,5};
for (int j = 0; j < i.length; j++) {
List_Of_Array.remove(i[j]-j);
}
System.out.println(List_Of_Array);
}
}
And the output was-
[A, C, E, G, H]
float widthRatio = Screen.PrimaryScreen.Bounds.Width / 1280;
float heightRatio = Screen.PrimaryScreen.Bounds.Height / 800f;
SizeF scale = new SizeF(widthRatio, heightRatio);
this.Scale(scale);
foreach (Control control in this.Controls)
{
control.Font = new Font("Verdana", control.Font.SizeInPoints * heightRatio * widthRatio);
}
try
{
// load the assembly or type
}
catch (Exception ex)
{
if (ex is System.Reflection.ReflectionTypeLoadException)
{
var typeLoadException = ex as ReflectionTypeLoadException;
var loaderExceptions = typeLoadException.LoaderExceptions;
}
}
In an elevated Command Prompt write this :
To disable:
bcdedit /set hypervisorlaunchtype off
To enable:
bcdedit /set hypervisorlaunchtype auto
(From comments - restart to take effect)
There is also bcgen (a PHP7 port of bcompiler):
https://github.com/vjardin/bcgen/
(PHP7.2 only)
This is one of Chris Komlenic's 8 Reasons Why MySQL's ENUM Data Type Is Evil:
4. Getting a list of distinct ENUM members is a pain.
A very common need is to populate a select-box or drop down list with possible values from the database. Like this:
Select color:
[ select box ]
If these values are stored in a reference table named 'colors', all you need is:
SELECT * FROM colors
...which can then be parsed out to dynamically generate the drop down list. You can add or change the colors in the reference table, and your sexy order forms will automatically be updated. Awesome.Now consider the evil ENUM: how do you extract the member list? You could query the ENUM column in your table for DISTINCT values but that will only return values that are actually used and present in the table, not necessarily all possible values. You can query INFORMATION_SCHEMA and parse them out of the query result with a scripting language, but that's unnecessarily complicated. In fact, I don't know of any elegant, purely SQL way to extract the member list of an ENUM column.
To get more than 20 you can use a load more button.
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Instagram more button example</title>
<!--
Instagram PHP API class @ Github
https://github.com/cosenary/Instagram-PHP-API
-->
<style>
article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }
ul {
width: 950px;
}
ul > li {
float: left;
list-style: none;
padding: 4px;
}
#more {
bottom: 8px;
margin-left: 80px;
position: fixed;
font-size: 13px;
font-weight: 700;
line-height: 20px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#more').click(function() {
var tag = $(this).data('tag'),
maxid = $(this).data('maxid');
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {
tag: tag,
max_id: maxid
},
dataType: 'json',
cache: false,
success: function(data) {
// Output data
$.each(data.images, function(i, src) {
$('ul#photos').append('<li><img src="' + src + '"></li>');
});
// Store new maxid
$('#more').data('maxid', data.next_id);
}
});
});
});
</script>
</head>
<body>
<?php
/**
* Instagram PHP API
*/
require_once 'instagram.class.php';
// Initialize class with client_id
// Register at http://instagram.com/developer/ and replace client_id with your own
$instagram = new Instagram('ENTER CLIENT ID HERE');
// Get latest photos according to geolocation for Växjö
// $geo = $instagram->searchMedia(56.8770413, 14.8092744);
$tag = 'sweden';
// Get recently tagged media
$media = $instagram->getTagMedia($tag);
// Display first results in a <ul>
echo '<ul id="photos">';
foreach ($media->data as $data)
{
echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
}
echo '</ul>';
// Show 'load more' button
echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>
</body>
</html>
ajax.php
<?php
/**
* Instagram PHP API
*/
require_once 'instagram.class.php';
// Initialize class for public requests
$instagram = new Instagram('ENTER CLIENT ID HERE');
// Receive AJAX request and create call object
$tag = $_GET['tag'];
$maxID = $_GET['max_id'];
$clientID = $instagram->getApiKey();
$call = new stdClass;
$call->pagination->next_max_id = $maxID;
$call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";
// Receive new data
$media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));
// Collect everything for json output
$images = array();
foreach ($media->data as $data) {
$images[] = $data->images->thumbnail->url;
}
echo json_encode(array(
'next_id' => $media->pagination->next_max_id,
'images' => $images
));
?>
instagram.class.php
Find the function getTagMedia() and replace with:
public function getTagMedia($name, $auth=false, $params=null) {
return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}
Hi,
Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.
Here how I do that...
# Accesible Index Page
<IfModule dir_module>
DirectoryIndex index.php index.html
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>
The above code simply captures any index.* and redirect it to the main domain.
Thank you
CSS:
#cols {
-moz-column-count: 3;
-moz-column-gap: 20px;
-webkit-column-count: 3;
-webkit-column-gap: 20px;
column-count: 3;
column-gap: 20px;
}
HTML
<div id="cols">
<ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
<li>List item 6</li>
<li>List item 7</li>
<li>List item 8</li>
<li>List item 9</li>
<li>List item 10</li>
<li>List item 11</li>
<li>List item 12</li>
<li>List item 10</li>
<li>List item 11</li>
<li>List item 12</li>
</ul>
</div>
Check demo : https://codepen.io/pen/
If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :
List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
tokens.add(inFile1.nextLine());
}
After that, if you need to, you can copy to an array :
String[] tokenArray = tokens.toArray(new String[0]);
If you are using the default R console, the key combination Option + Command + L will clear the console.
While a mutex may be used to solve other problems, the primary reason they exist is to provide mutual exclusion and thereby solve what is known as a race condition. When two (or more) threads or processes are attempting to access the same variable concurrently, we have potential for a race condition. Consider the following code
//somewhere long ago, we have i declared as int
void my_concurrently_called_function()
{
i++;
}
The internals of this function look so simple. It's only one statement. However, a typical pseudo-assembly language equivalent might be:
load i from memory into a register
add 1 to i
store i back into memory
Because the equivalent assembly-language instructions are all required to perform the increment operation on i, we say that incrementing i is a non-atmoic operation. An atomic operation is one that can be completed on the hardware with a gurantee of not being interrupted once the instruction execution has begun. Incrementing i consists of a chain of 3 atomic instructions. In a concurrent system where several threads are calling the function, problems arise when a thread reads or writes at the wrong time. Imagine we have two threads running simultaneoulsy and one calls the function immediately after the other. Let's also say that we have i initialized to 0. Also assume that we have plenty of registers and that the two threads are using completely different registers, so there will be no collisions. The actual timing of these events may be:
thread 1 load 0 into register from memory corresponding to i //register is currently 0
thread 1 add 1 to a register //register is now 1, but not memory is 0
thread 2 load 0 into register from memory corresponding to i
thread 2 add 1 to a register //register is now 1, but not memory is 0
thread 1 write register to memory //memory is now 1
thread 2 write register to memory //memory is now 1
What's happened is that we have two threads incrementing i concurrently, our function gets called twice, but the outcome is inconsistent with that fact. It looks like the function was only called once. This is because the atomicity is "broken" at the machine level, meaning threads can interrupt each other or work together at the wrong times.
We need a mechanism to solve this. We need to impose some ordering to the instructions above. One common mechanism is to block all threads except one. Pthread mutex uses this mechanism.
Any thread which has to execute some lines of code which may unsafely modify shared values by other threads at the same time (using the phone to talk to his wife), should first be made acquire a lock on a mutex. In this way, any thread that requires access to the shared data must pass through the mutex lock. Only then will a thread be able to execute the code. This section of code is called a critical section.
Once the thread has executed the critical section, it should release the lock on the mutex so that another thread can acquire a lock on the mutex.
The concept of having a mutex seems a bit odd when considering humans seeking exclusive access to real, physical objects but when programming, we must be intentional. Concurrent threads and processes don't have the social and cultural upbringing that we do, so we must force them to share data nicely.
So technically speaking, how does a mutex work? Doesn't it suffer from the same race conditions that we mentioned earlier? Isn't pthread_mutex_lock() a bit more complex that a simple increment of a variable?
Technically speaking, we need some hardware support to help us out. The hardware designers give us machine instructions that do more than one thing but are guranteed to be atomic. A classic example of such an instruction is the test-and-set (TAS). When trying to acquire a lock on a resource, we might use the TAS might check to see if a value in memory is 0. If it is, that would be our signal that the resource is in use and we do nothing (or more accurately, we wait by some mechanism. A pthreads mutex will put us into a special queue in the operating system and will notify us when the resource becomes available. Dumber systems may require us to do a tight spin loop, testing the condition over and over). If the value in memory is not 0, the TAS sets the location to something other than 0 without using any other instructions. It's like combining two assembly instructions into 1 to give us atomicity. Thus, testing and changing the value (if changing is appropriate) cannot be interrupted once it has begun. We can build mutexes on top of such an instruction.
Note: some sections may appear similar to an earlier answer. I accepted his invite to edit, he preferred the original way it was, so I'm keeping what I had which is infused with a little bit of his verbiage.
sometimes when programming recursivly, you call the function with the same parameters multiple times which is unnecassary.
The famous example Fibonacci numbers:
index: 1,2,3,4,5,6...
Fibonacci number: 1,1,2,3,5,8...
function F(n) {
if (n < 3)
return 1
else
return F(n-1) + F(n-2)
}
Let's run F(5):
F(5) = F(4) + F(3)
= {F(3)+F(2)} + {F(2)+F(1)}
= {[F(2)+F(1)]+1} + {1+1}
= 1+1+1+1+1
So we have called : 1 times F(4) 2 times F(3) 3 times F(2) 2 times F(1)
Dynamic Programming approach: if you call a function with the same parameter more than once, save the result into a variable to directly access it on next time. The iterative way:
if (n==1 || n==2)
return 1
else
f1=1, f2=1
for i=3 to n
f = f1 + f2
f1 = f2
f2 = f
Let's call F(5) again:
fibo1 = 1
fibo2 = 1
fibo3 = (fibo1 + fibo2) = 1 + 1 = 2
fibo4 = (fibo2 + fibo3) = 1 + 2 = 3
fibo5 = (fibo3 + fibo4) = 2 + 3 = 5
As you can see, whenever you need the multiple call you just access the corresponding variable to get the value instead of recalculating it.
By the way, dynamic programming doesn't mean to convert a recursive code into an iterative code. You can also save the subresults into a variable if you want a recursive code. In this case the technique is called memoization. For our example it looks like this:
// declare and initialize a dictionary
var dict = new Dictionary<int,int>();
for i=1 to n
dict[i] = -1
function F(n) {
if (n < 3)
return 1
else
{
if (dict[n] == -1)
dict[n] = F(n-1) + F(n-2)
return dict[n]
}
}
So the relationship to the Divide and Conquer is that D&D algorithms rely on recursion. And some versions of them has this "multiple function call with the same parameter issue." Search for "matrix chain multiplication" and "longest common subsequence" for such examples where DP is needed to improve the T(n) of D&D algo.
Since it's C++ why not to use std::string
instead of char*
?
Concatenation will be trivial:
std::string str = "abc";
str += "another";
Due to the popularity of MySQL, there's no wonder Lock wait timeout exceeded; try restarting transaction exception gets so much attention on SO.
The more contention you have, the greater the chance of deadlocks, which a DB engine will resolve by time-outing one of the deadlocked transactions.
Also, long-running transactions that have modified (e.g. UPDATE
or DELETE
) a large number of entries are more likely to generate conflicts with other transactions.
Although InnoDB MVCC, you can still request explicit locks using the FOR UPDATE
clause. However, unlike other popular DBs (Oracle, MSSQL, PostgreSQL, DB2), MySQL uses REPEATABLE_READ
as the default isolation level.
Now, the locks that you acquired (either by modifying rows or using explicit locking), are held for the duration of the currently running transaction. If you want a good explanation of the difference between REPEATABLE_READ
and READ COMMITTED
in regards to locking, please read this Percona article.
In REPEATABLE READ every lock acquired during a transaction is held for the duration of the transaction.
In READ COMMITTED the locks that did not match the scan are released after the STATEMENT completes.
...
This means that in READ COMMITTED other transactions are free to update rows that they would not have been able to update (in REPEATABLE READ) once the UPDATE statement completes.
Therefore: The more restrictive the isolation level (REPEATABLE_READ
, SERIALIZABLE
) the greater the chance of deadlock. This is not an issue "per se", it's a trade-off.
You can get very good results with READ_COMMITED
, as you need application-level lost update prevention when using logical transactions that span over multiple HTTP requests. The optimistic locking approach targets lost updates that might happen even if you use the SERIALIZABLE
isolation level while reducing the lock contention by allowing you to use READ_COMMITED
.
In my case solution was to change permission to app/storage/framework/views
and app/storage/logs
directories.
Select Product
from formula bar in your answer cell.
Select cells you want to multiply.
The short answer for this is, "because that's what the C++ standard specifies".
Note that you can always specify a constructor that's different from the default, like so:
class Shape {
Shape() {...} //default constructor
Shape(int h, int w) {....} //some custom constructor
};
class Rectangle : public Shape {
Rectangle(int h, int w) : Shape(h, w) {...} //you can specify which base class constructor to call
}
The default constructor of the base class is called only if you don't specify which one to call.
I went to My workspace
directory/.metadata/.plugins/org.eclipse.core.runtime/.settings/
and then deleted all recently added files !!
If you want to wrap your text but maintain alignment then you can wrap that cell in a minipage
or varwidth
environment (varwidth comes from the varwidth package). Varwidth will be "as wide as it's contents but no wider than X". You can create a custom column type which acts like "p{xx}" but shrinks to fit by using
\newcolumntype{M}[1]{>{\begin{varwidth}[t]{#1}}l<{\end{varwidth}}}
which may require the array
package. Then when you use something like \begin{tabular}{llM{2in}}
the first two columns we be normal left-aligned and the third column will be normal left aligned but if it gets wider than 2in then the text will be wrapped.
-w
is the GCC-wide option to disable warning messages.
I noticed no one has mentioned achieving this through environment variables (CI/CD friendly).
export PLAY_HTTP_PORT=1234
export PLAY_HTTPS_PORT=1235
Once set, Play will read from those environment variables to determine the port when doing sbt run
, sbt start
, or when running the executable for prod deployment. See the docs for more.
If using SSH config file, my issue was that ~/.ssh/config
was not specified correct. From Enabling SSH connections over HTTPS
Host github.com
Hostname ssh.github.com
Port 443
The NEW values (or NEW_BUFFER as you have renamed them) are only available when INSERTING and UPDATING. For DELETING you would need to use OLD (OLD_BUFFER). So your trigger would become:
CREATE or REPLACE TRIGGER test001
AFTER INSERT OR DELETE OR UPDATE ON tabletest001
REFERENCING OLD AS old_buffer NEW AS new_buffer
FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')
You may need to add logic inside the trigger to cater for code that updates field1 from 'HBP000' to something else.
The object itself will not change. The main difference between these 2 keyword is the use:
In the CSS or Javascript files:
The Wikipedia newline article might help you out. Here is an excerpt:
The different newline conventions often cause text files that have been transferred between systems of different types to be displayed incorrectly. For example, files originating on Unix or Apple Macintosh systems may appear as a single long line on some programs running on Microsoft Windows. Conversely, when viewing a file originating from a Windows computer on a Unix system, the extra CR may be displayed as ^M or at the end of each line or as a second line break.
This is for Android Studio 1.0.2(Windows7). Right click on the project on project bar and delete.
Then remove the project folder from within your user folder under 'AndroidStudioProject' using Windows explorer.
Close the studio and relaunch you will presented with welcome screen. Click on deleted project from left side pane then select the option to remove from the list. Done!
do not change the props directly in components.if you need change it set a new property like this:
data () {
return () {
listClone: this.list
}
}
And change the value of listClone.
Just ot note: Pycharm's to spaces function only works on indent tabs at the beginning of a line, not interstitial tabs within a line of text. for example, when you are trying to format columns in monospaced text.
You can do it with few lines of CSS code. You can align all div's which you want to appear next to each other to right.
<div class="div_r">First Element</div>
<div class="div_r">Second Element</div>
<style>
.div_r{
float:right;
color:red;
}
</style>
Use insert
:
In [1]: ls = [1,2,3]
In [2]: ls.insert(0, "new")
In [3]: ls
Out[3]: ['new', 1, 2, 3]
declare @T int
set @T = 10455836
--set @T = 421151
select (@T / 1000000) % 100 as hour,
(@T / 10000) % 100 as minute,
(@T / 100) % 100 as second,
(@T % 100) * 10 as millisecond
select dateadd(hour, (@T / 1000000) % 100,
dateadd(minute, (@T / 10000) % 100,
dateadd(second, (@T / 100) % 100,
dateadd(millisecond, (@T % 100) * 10, cast('00:00:00' as time(2))))))
Result:
hour minute second millisecond
----------- ----------- ----------- -----------
10 45 58 360
(1 row(s) affected)
----------------
10:45:58.36
(1 row(s) affected)
So probably not the best solution, but seems to work OK.
<IFRAME ID=myframe SRC=.... ></IFRAME>
<SCRIPT>
window.onload = function(){document.getElementById('myframe').contentWindow.document.body.style = 'zoom:50%;';};
</SCRIPT>
Obviously not trying to fix the parent, just adding the "zoom:50%" style to the body of the child with a bit of javascript.
Maybe could set the style of the "HTML" element, but didn't try that.
The only conditions available in CSS are selectors and @media. Some browsers support some of the CSS 3 selectors and media queries.
You can modify an element with JavaScript to change if it matches a selector or not (e.g. by adding a new class).
Ruby has eleven methods to find elements in an array.
The preferred one is include?
or, for repeated access, creat a Set and then call include?
or member?
.
Here are all of them:
array.include?(element) # preferred method
array.member?(element)
array.to_set.include?(element)
array.to_set.member?(element)
array.index(element) > 0
array.find_index(element) > 0
array.index { |each| each == element } > 0
array.find_index { |each| each == element } > 0
array.any? { |each| each == element }
array.find { |each| each == element } != nil
array.detect { |each| each == element } != nil
They all return a true
ish value if the element is present.
include?
is the preferred method. It uses a C-language for
loop internally that breaks when an element matches the internal rb_equal_opt/rb_equal
functions. It cannot get much more efficient unless you create a Set for repeated membership checks.
VALUE
rb_ary_includes(VALUE ary, VALUE item)
{
long i;
VALUE e;
for (i=0; i<RARRAY_LEN(ary); i++) {
e = RARRAY_AREF(ary, i);
switch (rb_equal_opt(e, item)) {
case Qundef:
if (rb_equal(e, item)) return Qtrue;
break;
case Qtrue:
return Qtrue;
}
}
return Qfalse;
}
member?
is not redefined in the Array
class and uses an unoptimized implementation from the Enumerable
module that literally enumerates through all elements:
static VALUE
member_i(RB_BLOCK_CALL_FUNC_ARGLIST(iter, args))
{
struct MEMO *memo = MEMO_CAST(args);
if (rb_equal(rb_enum_values_pack(argc, argv), memo->v1)) {
MEMO_V2_SET(memo, Qtrue);
rb_iter_break();
}
return Qnil;
}
static VALUE
enum_member(VALUE obj, VALUE val)
{
struct MEMO *memo = MEMO_NEW(val, Qfalse, 0);
rb_block_call(obj, id_each, 0, 0, member_i, (VALUE)memo);
return memo->v2;
}
Translated to Ruby code this does about the following:
def member?(value)
memo = [value, false, 0]
each_with_object(memo) do |each, memo|
if each == memo[0]
memo[1] = true
break
end
memo[1]
end
Both include?
and member?
have O(n) time complexity since the both search the array for the first occurrence of the expected value.
We can use a Set to get O(1) access time at the cost of having to create a Hash representation of the array first. If you repeatedly check membership on the same array this initial investment can pay off quickly. Set
is not implemented in C but as plain Ruby class, still the O(1) access time of the underlying @hash
makes this worthwhile.
Here is the implementation of the Set class:
module Enumerable
def to_set(klass = Set, *args, &block)
klass.new(self, *args, &block)
end
end
class Set
def initialize(enum = nil, &block) # :yields: o
@hash ||= Hash.new
enum.nil? and return
if block
do_with_enum(enum) { |o| add(block[o]) }
else
merge(enum)
end
end
def merge(enum)
if enum.instance_of?(self.class)
@hash.update(enum.instance_variable_get(:@hash))
else
do_with_enum(enum) { |o| add(o) }
end
self
end
def add(o)
@hash[o] = true
self
end
def include?(o)
@hash.include?(o)
end
alias member? include?
...
end
As you can see the Set class just creates an internal @hash
instance, maps all objects to true
and then checks membership using Hash#include?
which is implemented with O(1) access time in the Hash class.
I won't discuss the other seven methods as they are all less efficient.
There are actually even more methods with O(n) complexity beyond the 11 listed above, but I decided to not list them since they scan the entire array rather than breaking at the first match.
Don't use these:
# bad examples
array.grep(element).any?
array.select { |each| each == element }.size > 0
...
OPTIONS tells you things such as "What methods are allowed for this resource".
HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.
For future users. @keshavDulal answer doesn't work for latest version. And I couldn't find a proper fix for the issues that are reporting in the latest version 3.3.3
.
Anyway I finally fixed it after researching a bit. Here is the solution for winston version 3.3.3
Install winston and winston-daily-rotate-file
npm install winston
npm install winston-daily-rotate-file
Create a new file utils/logger.js
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
var logger = new winston.createLogger({
transports: [
new (winston.transports.DailyRotateFile)({
name: 'access-file',
level: 'info',
filename: './logs/access.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
}),
new (winston.transports.DailyRotateFile)({
name: 'error-file',
level: 'error',
filename: './logs/error.log',
json: false,
datePattern: 'yyyy-MM-DD',
prepend: true,
maxFiles: 10
})
]
});
module.exports = {
logger
};
Then in any file where you want to use logging import the module like
const logger = require('./utils/logger').logger;
Use logger like the following:
logger.info('Info service started');
logger.error('Service crashed');
To follow up on Theo's suggestion with my findings (apologies - I don't currently have enough reputation to post this as a comment)
First, this is how to use several named parameters:
String commandString = "INSERT INTO Users (Name, Desk, UpdateTime) VALUES (:Name, :Desk, :UpdateTime)";
using (OracleCommand command = new OracleCommand(commandString, _connection, _transaction))
{
command.Parameters.Add("Name", OracleType.VarChar, 50).Value = strategy;
command.Parameters.Add("Desk", OracleType.VarChar, 50).Value = deskName ?? OracleString.Null;
command.Parameters.Add("UpdateTime", OracleType.DateTime).Value = updated;
command.ExecuteNonQuery();
}
However, I saw no variation in speed between:
I'm using System.Data.OracleClient, deleting and inserting 2500 rows inside a transaction
You can try in this way.
for(int a=5;a>0;a--){
int b=0;
for(b=0;b<a;b++){
System.out.print(" ");
}
for (int j=b;j<5;j++){
System.out.print(" $ ");
}
System.out.println("");
}
Out put
$
$ $
$ $ $
$ $ $ $
This problem will solve when we change the version of apache-maven
I faced it and it was solved when i used apache-maven-2.2.1
overload operator<<:
template<typename OutStream, typename T>
OutStream& operator<< (OutStream& out, const vector<T>& v)
{
for (auto const& tmp : v)
out << tmp << " ";
out << endl;
return out;
}
Usage:
vector <int> test {1,2,3};
wcout << test; // or any output stream
In google chrome element.value return the name + the path, but a fake path. Thus, for my case I used the name attribute on the file like below :
function getFileData(myFile){
var file = myFile.files[0];
var filename = file.name;
}
this is the call from the page :
<input id="ph1" name="photo" type="file" class="jq_req" onchange="getFileData(this);"/>
Another option is to use HttpStatus
class from the Apache commons-httpclient which provides you the various Http statuses as constants.
After adding curl.exe's path to the System Variable 'Path'
you can open command prompt and run 'curl -V' to see if it is working.
I think I've seen something similar when folders were moved on the server but the working copies were still bound to the older SVN folder structure. Not sure if anyone moved things around in your trunk before you had the chance to merge the branch.
Is that a possibility?
IIS sessions timeout value is for classic .asp applications only, this is controlled on IIS configuration. In your case For ASP.NET apps, only the web.config-specified timeout value applies.
The following incorporates Dag Hjermann's basic data and programming, improves upon user4786271's strategy to create a "transformation function" to optimally combine the plots and data axis, and responds to baptist's note that such a function can be created within R.
#Climatogram for Oslo (1961-1990)
climate <- tibble(
Month = 1:12,
Temp = c(-4,-4,0,5,11,15,16,15,11,6,1,-3),
Precip = c(49,36,47,41,53,65,81,89,90,84,73,55))
#y1 identifies the position, relative to the y1 axis,
#the locations of the minimum and maximum of the y2 graph.
#Usually this will be the min and max of y1.
#y1<-(c(max(climate$Precip), 0))
#y1<-(c(150, 55))
y1<-(c(max(climate$Precip), min(climate$Precip)))
#y2 is the Minimum and maximum of the secondary axis data.
y2<-(c(max(climate$Temp), min(climate$Temp)))
#axis combines y1 and y2 into a dataframe used for regressions.
axis<-cbind(y1,y2)
axis<-data.frame(axis)
#Regression of Temperature to Precipitation:
T2P<-lm(formula = y1 ~ y2, data = axis)
T2P_summary <- summary(lm(formula = y1 ~ y2, data = axis))
T2P_summary
#Identifies the intercept and slope of regressing Temperature to Precipitation:
T2PInt<-T2P_summary$coefficients[1, 1]
T2PSlope<-T2P_summary$coefficients[2, 1]
#Regression of Precipitation to Temperature:
P2T<-lm(formula = y2 ~ y1, data = axis)
P2T_summary <- summary(lm(formula = y2 ~ y1, data = axis))
P2T_summary
#Identifies the intercept and slope of regressing Precipitation to Temperature:
P2TInt<-P2T_summary$coefficients[1, 1]
P2TSlope<-P2T_summary$coefficients[2, 1]
#Create Plot:
ggplot(climate, aes(Month, Precip)) +
geom_col() +
geom_line(aes(y = T2PSlope*Temp + T2PInt), color = "red") +
scale_y_continuous("Precipitation", sec.axis = sec_axis(~.*P2TSlope + P2TInt, name = "Temperature")) +
scale_x_continuous("Month", breaks = 1:12) +
theme(axis.line.y.right = element_line(color = "red"),
axis.ticks.y.right = element_line(color = "red"),
axis.text.y.right = element_text(color = "red"),
axis.title.y.right = element_text(color = "red")) +
ggtitle("Climatogram for Oslo (1961-1990)")
Most noteworthy is that a new "transformation function" works better with just two data points from the data set of each axes—usually the maximum and minimum values of each set. The resulting slopes and intercepts of the two regressions enable ggplot2 to exactly pair the plots of the minimums and maximums of each axis. As user4786271 pointed out, the two regressions transform each data set and plot to the other. One transforms the break points of the first y axis to the values of the second y axis. The second transforms the data of the secondary y axis to be "normalized" according to the first y axis. The following output shows how the axis align the minimums and maximums of each dataset:
Having the maximums and minimums match may be most appropriate; however, another benefit of this method is that the plot associated with the secondary axis can be easily shifted, if desired, by altering a programming line related to the primary axis data. The output below simply changes the minimum precipitation input in the programming line of y1 to "0", and thus aligns the minimum Temperature level with the "0" Precipitation level.
From: y1<-(c(max(climate$Precip), min(climate$Precip)))
To: y1<-(c(max(climate$Precip), 0))
Notice how the resulting new regressions and ggplot2 automatically adjusted the plot and axis to correctly align the minimum Temperature to the new "base" of the "0" Precipitation level. Likewise, one is easily able to elevate the Temperature plot so that it is more obvious. The following graph is created by simply changing the above-noted line to:
"y1<-(c(150, 55))"
The above line tells the maximum of the Temperature graph to coincide with the "150" Precipitation level, and the minimum of the temperature line to coincide with the "55" Precipitation level. Again, notice how ggplot2 and the resulting new regression outputs enable the graph to maintain correct alignment with the axis.
The above may not be a desirable output; however, it is an example of how the graph can be easily manipulated and still have correct relationships between the plots and the axis. The incorporation of Dag Hjermann's theme improves identification of the axis corresponding to the plot.
For at DataFrame one can simply type
head(data, num=10L)
to get the first 10 for example.
For a data.frame one can simply type
head(data, 10)
to get the first 10.
Try:
Install all the required tools and configurations using Microsoft's windows-build-tools by running npm install -g windows-build-tools
from an elevated PowerShell (run as Administrator).
You almost got it. It should be this:
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
The value in for
should be the id of the element you are labeling.
To do that you should do:
a = [5, 7, 11, 4, 5]
for i in range(len(a)-1):
print [a[i], a[i+1]]
You can change the tabs by ctrl-pgup and ctrl-pgdown. On that tab you came from the NERDTree is still selected and you can open another tab.
Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:
def someMethod(def args) {
println "MANDATORY1=${args.mandatory1}"
println "MANDATORY2=${args.mandatory2}"
println "OPTIONAL1=${args?.optional1}"
println "OPTIONAL2=${args?.optional2}"
}
someMethod mandatory1:1, mandatory2:2, optional1:3
with the output:
MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null
This looks nicer and the advantage of this is that you can change the order of the parameters as you like.
Actually, the onclick events will NOT fire when the user uses the keyboard to change the selection in the select control. You might have to use a combination of onChange and onClick to get the behavior you're looking for.
Copy the global variable to a variable in the scope in your controller.
function MyCtrl($scope) {
$scope.variable1 = variable1;
}
Then you can just access it like you tried. But note that this variable will not change when you change the global variable. If you need that, you could instead use a global object and "copy" that. As it will be "copied" by reference, it will be the same object and thus changes will be applied (but remember that doing stuff outside of AngularJS will require you to do $scope.$apply anway).
But maybe it would be worthwhile if you would describe what you actually try to achieve. Because using a global variable like this is almost never a good idea and there is probably a better way to get to your intended result.
Span does not have 'change' event by default. But you can add this event manually.
Listen to the change event of span.
$("#span1").on('change',function(){
//Do calculation and change value of other span2,span3 here
$("#span2").text('calculated value');
});
And wherever you change the text in span1. Trigger the change event manually.
$("#span1").text('test').trigger('change');
Swift 4.2 and Swift 5 colorise parts of the string.
A very easy way to use NSMutableAttributedString while extending the String. This also can be used to colourize more than one word in the whole string.
Add new file for extensions, File -> New -> Swift File with name for ex. "NSAttributedString+TextColouring" and add the code
import UIKit
extension String {
func attributedStringWithColor(_ strings: [String], color: UIColor, characterSpacing: UInt? = nil) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
for string in strings {
let range = (self as NSString).range(of: string)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
}
guard let characterSpacing = characterSpacing else {return attributedString}
attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSRange(location: 0, length: attributedString.length))
return attributedString
}
}
Now you can use globally at any viewcontroller you want:
let attributedWithTextColor: NSAttributedString = "Doc, welcome back :)".attributedStringWithColor(["Doc", "back"], color: UIColor.black)
myLabel.attributedText = attributedWithTextColor
Cited from
Apple Developer Relations
10-Oct-2014 09:12 PM
After much deliberation, engineering has removed this feature. The file
/etc/launchd.conf
was intentionally removed for security reasons. As a workaround, you could runlaunchctl limit
as root early during boot, perhaps from aLaunchDaemon
. (...)
Solution:
Put code in to
/Library/LaunchDaemons/com.apple.launchd.limit.plist
by bash-script:
#!/bin/bash
echo '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>eicar</string>
<key>ProgramArguments</key>
<array>
<string>/bin/launchctl</string>
<string>limit</string>
<string>core</string>
<string>unlimited</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>ServiceIPC</key>
<false/>
</dict>
</plist>' | sudo tee /Library/LaunchDaemons/com.apple.launchd.limit.plist
if you build an MVC project, its included by default. otherwise, what Nick said.
Purpose is different:
The transient
keyword and @Transient
annotation have two different purposes: one deals with serialization and one deals with persistence. As programmers, we often marry these two concepts into one, but this is not accurate in general. Persistence refers to the characteristic of state that outlives the process that created it. Serialization in Java refers to the process of encoding/decoding an object's state as a byte stream.
The transient
keyword is a stronger condition than @Transient
:
If a field uses the transient
keyword, that field will not be serialized when the object is converted to a byte stream. Furthermore, since JPA treats fields marked with the transient
keyword as having the @Transient
annotation, the field will not be persisted by JPA either.
On the other hand, fields annotated @Transient
alone will be converted to a byte stream when the object is serialized, but it will not be persisted by JPA. Therefore, the transient
keyword is a stronger condition than the @Transient
annotation.
Example
This begs the question: Why would anyone want to serialize a field that is not persisted to the application's database? The reality is that serialization is used for more than just persistence. In an Enterprise Java application there needs to be a mechanism to exchange objects between distributed components; serialization provides a common communication protocol to handle this. Thus, a field may hold critical information for the purpose of inter-component communication; but that same field may have no value from a persistence perspective.
For example, suppose an optimization algorithm is run on a server, and suppose this algorithm takes several hours to complete. To a client, having the most up-to-date set of solutions is important. So, a client can subscribe to the server and receive periodic updates during the algorithm's execution phase. These updates are provided using the ProgressReport
object:
@Entity
public class ProgressReport implements Serializable{
private static final long serialVersionUID = 1L;
@Transient
long estimatedMinutesRemaining;
String statusMessage;
Solution currentBestSolution;
}
The Solution
class might look like this:
@Entity
public class Solution implements Serializable{
private static final long serialVersionUID = 1L;
double[][] dataArray;
Properties properties;
}
The server persists each ProgressReport
to its database. The server does not care to persist estimatedMinutesRemaining
, but the client certainly cares about this information. Therefore, the estimatedMinutesRemaining
is annotated using @Transient
. When the final Solution
is located by the algorithm, it is persisted by JPA directly without using a ProgressReport
.
To check online you can use
http://codebeautify.org/base64-to-image-converter
You can convert string to image like this way
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.ByteArrayOutputStream;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView image =(ImageView)findViewById(R.id.image);
//encode image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
//decode base64 string to image
imageBytes = Base64.decode(imageString, Base64.DEFAULT);
Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
image.setImageBitmap(decodedImage);
}
}
From the docs
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
As you say:
error: missing method body, or declare abstract public static void main(String[] args); ^ this is what i got after i added it after the class name
You probably haven't declared main with a body (as ';" would suggest in your error).
You need to have main method with a body, which means you need to add { and }:
public static void main(String[] args) {
}
Add it inside your class definition.
Although sometimes error messages are not very clear, most of the time they contain enough information to point to the issue. Worst case, you can search internet for the error message. Also, documentation can be really helpful.
on sql 2008 this is valid
DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable
on sql server 2005, you need to do this
DECLARE @myVariable nvarchar(Max)
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable
Nginx works as a front end server, which in this case proxies the requests to a node.js server. Therefore you need to setup an nginx config file for node.
This is what I have done in my Ubuntu box:
Create the file yourdomain.com
at /etc/nginx/sites-available/
:
vim /etc/nginx/sites-available/yourdomain.com
In it you should have something like:
# the IP(s) on which your node server is running. I chose port 3000.
upstream app_yourdomain {
server 127.0.0.1:3000;
keepalive 8;
}
# the nginx server instance
server {
listen 80;
listen [::]:80;
server_name yourdomain.com www.yourdomain.com;
access_log /var/log/nginx/yourdomain.com.log;
# pass the request to the node.js server with the correct headers
# and much more can be added, see nginx config options
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://app_yourdomain/;
proxy_redirect off;
}
}
If you want nginx (>= 1.3.13) to handle websocket requests as well, add the following lines in the location /
section:
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
Once you have this setup you must enable the site defined in the config file above:
cd /etc/nginx/sites-enabled/
ln -s /etc/nginx/sites-available/yourdomain.com yourdomain.com
Create your node server app at /var/www/yourdomain/app.js
and run it at localhost:3000
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');
Test for syntax mistakes:
nginx -t
Restart nginx:
sudo /etc/init.d/nginx restart
Lastly start the node server:
cd /var/www/yourdomain/ && node app.js
Now you should see "Hello World" at yourdomain.com
One last note with regards to starting the node server: you should use some kind of monitoring system for the node daemon. There is an awesome tutorial on node with upstart and monit.
Another solution, without regard to security (I also think it is better to keep the credentials in another file or in a database) is to encrypt the password with gpg and insert it in the script.
I use a password-less gpg key pair that I keep in a usb. (Note: When you export this key pair don't use --armor, export them in binary format).
First encrypt your password:
EDIT: Put a space before this command, so it is not recorded by the bash history.
echo -n "pAssw0rd" | gpg --armor --no-default-keyring --keyring /media/usb/key.pub --recipient [email protected] --encrypt
That will be print out the gpg encrypted password in the standart output. Copy the whole message and add this to the script:
password=$(gpg --batch --quiet --no-default-keyring --secret-keyring /media/usb/key.priv --decrypt <<EOF
-----BEGIN PGP MESSAGE-----
hQEMA0CjbyauRLJ8AQgAkZT5gK8TrdH6cZEy+Ufl0PObGZJ1YEbshacZb88RlRB9
h2z+s/Bso5HQxNd5tzkwulvhmoGu6K6hpMXM3mbYl07jHF4qr+oWijDkdjHBVcn5
0mkpYO1riUf0HXIYnvCZq/4k/ajGZRm8EdDy2JIWuwiidQ18irp07UUNO+AB9mq8
5VXUjUN3tLTexg4sLZDKFYGRi4fyVrYKGsi0i5AEHKwn5SmTb3f1pa5yXbv68eYE
lCVfy51rBbG87UTycZ3gFQjf1UkNVbp0WV+RPEM9JR7dgR+9I8bKCuKLFLnGaqvc
beA3A6eMpzXQqsAg6GGo3PW6fMHqe1ZCvidi6e4a/dJDAbHq0XWp93qcwygnWeQW
Ozr1hr5mCa+QkUSymxiUrRncRhyqSP0ok5j4rjwSJu9vmHTEUapiyQMQaEIF2e2S
/NIWGg==
=uriR
-----END PGP MESSAGE-----
EOF)
In this way only if the usb is mounted in the system the password can be decrypted. Of course you can also import the keys into the system (less secure, or no security at all) or you can protect the private key with password (so it can not be automated).
Highlight the error and press "ALT+ENTER", you'll see an option to:
Add Library dependency > Edit Intention settings
This will bring you to a menu where you'll see the specific problem support dependency that differs with support-compat. Create its dependency in gradle (com 'XXX') and set it's version to match that of support-compat. Sync gradle and you're done.
For what it's worth, the ultimate shortcut:
In my .bash_profile
I have alias push="git push origin HEAD"
, so whenever i type push
I know I'm pushing to the current branch I'm on.
Use the .Clear
method.
Sheets("Test").Range("A1:C3").Clear
Consider John Doe a document rather than a collection
Give it a collection of things and thingsSharedWithOthers
Then you can map and query John Doe's shared things in that parallel thingsSharedWithOthers collection.
proprietary: "John Doe"(a document)
things(collection of John's things documents)
thingsSharedWithOthers(collection of John's things being shared with others):
[thingId]:
{who: "[email protected]", when:timestamp}
{who: "[email protected]", when:timestamp}
then set thingsSharedWithOthers
firebase.firestore()
.collection('thingsSharedWithOthers')
.set(
{ [thingId]:{ who: "[email protected]", when: new Date() } },
{ merge: true }
)
What solved the problem for me was - create a folder "drawable" in "..platforms/android/res/" and put "icon.png" in it.
You can check the android VLC it can stream and play video, if you want to indagate more, you can check their GIT to analyze what their do. Good luck!
Use (V3 version):
(Get-Content c:\temp\test.txt).replace('[MYID]', 'MyValue') | Set-Content c:\temp\test.txt
Or for V2:
(Get-Content c:\temp\test.txt) -replace '\[MYID\]', 'MyValue' | Set-Content c:\temp\test.txt
I wanted to send email using SMTPLIB, its easier and it does not require local setup. After other answers were not directly helpful, This is what i did.
Open Outlook in a browser; Go to the top right corner, click the gear icon for Settings, Choose 'Options' from the appearing drop-down list. Go to 'Accounts', click 'Pop and Imap', You will see the option: "Let devices and apps use pop",
Choose Yes option and Save changes.
Here is the code there after; Edit where neccesary. Most Important thing is to enable POP and the server code herein;
import smtplib
body = 'Subject: Subject Here .\nDear ContactName, \n\n' + 'Email\'s BODY text' + '\nYour :: Signature/Innitials'
try:
smtpObj = smtplib.SMTP('smtp-mail.outlook.com', 587)
except Exception as e:
print(e)
smtpObj = smtplib.SMTP_SSL('smtp-mail.outlook.com', 465)
#type(smtpObj)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('[email protected]', "password")
smtpObj.sendmail('[email protected]', '[email protected]', body) # Or recipient@outlook
smtpObj.quit()
pass
From my experience in SQL Server,I found one of the scenarios where CTE outperformed Temp table
I needed to use a DataSet(~100000) from a complex Query just ONCE in my stored Procedure.
Temp table was causing an overhead on SQL where my Procedure was performing slowly(as Temp Tables are real materialized tables that exist in tempdb and Persist for the life of my current procedure)
On the other hand, with CTE, CTE Persist only until the following query is run. So, CTE is a handy in-memory structure with limited Scope. CTEs don't use tempdb by default.
This is one scenario where CTEs can really help simplify your code and Outperform Temp Table. I had Used 2 CTEs, something like
WITH CTE1(ID, Name, Display)
AS (SELECT ID,Name,Display from Table1 where <Some Condition>),
CTE2(ID,Name,<col3>) AS (SELECT ID, Name,<> FROM CTE1 INNER JOIN Table2 <Some Condition>)
SELECT CTE2.ID,CTE2.<col3>
FROM CTE2
GO
Use this: http://winginx.com/htaccess
Online converter, nice way and time saver ;)
if your are using ES5 syntax then you need to bind it properly
this.delta = this.delta.bind(this)
and if you are using ES6 and above you can use arrow function, then you don't need to use bind() it
delta = () => {
// do something
}
BeRecursive's answer is the one I used, so that we could standardize on Json.Net (we have MVC5 and WebApi 5 -- WebApi 5 already uses Json.Net), but I found an issue. When you have parameters in your route to which you're POSTing, MVC tries to call the model binder for the URI values, and this code will attempt to bind the posted JSON to those values.
Example:
[HttpPost]
[Route("Customer/{customerId:int}/Vehicle/{vehicleId:int}/Policy/Create"]
public async Task<JsonNetResult> Create(int customerId, int vehicleId, PolicyRequest policyRequest)
The BindModel
function gets called three times, bombing on the first, as it tries to bind the JSON to customerId
with the error: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.
I added this block of code to the top of BindModel
:
if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) {
return base.BindModel(controllerContext, bindingContext);
}
The ValueProvider, fortunately, has route values figured out by the time it gets to this method.
This worked for me within an ASP.NET site. To enable validation on some hidden fields use this code
$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";
To enable validation for all elements of form use this one
$("form").data("validator").settings.ignore = "";
Note that use them within $(document).ready(function() { })
Like @wesley says, you have not closed your first <td>
. You opened it two times.
<table class="list1">
<tr>
<td>1</td><td>a</td>
</tr>
<tr>
<td>2</td><td>b</td>
</tr>
<tr>
<td>3</td><td>c</td>
</tr>
</table>
CSS:
.list1 tr:hover{
background-color:#fefefe;
}
There is no JavaScript needed, just complete your HTML code
select from_unixtime(column,'%Y-%m-%d') from myTable;
Solution who works with Lumen 5.5 with foreign keys constraints :
$categories = MusicCategory::all();
foreach($categories as $category)
{
$category->delete();
}
return response()->json(['error' => false]);
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
Sometimes spacing and Order of parameters in connection string matters (based on personal experience and a long night :S)
So stick to the standard format here
Server=myServerAddress; Port=1234; Database=myDataBase; Uid=myUsername; Pwd=myPassword;
For anyone else that may encounter this problem and it is not solved by either of the options above, this is what worked for me.
1. Click on the website in IIS
2. Double Click on Authentication under IIS
3. Enable Anonymous Authentication
I had disabled this because we were using our own Auth, but that lead to this same problem and the accepted answer did not help in any way.
You have to search in the array like:
function changeDesc( value, desc ) {
for (var i in projects) {
if (projects[i].value == value) {
projects[i].desc = desc;
break; //Stop this loop, we found it!
}
}
}
and use it like
var projects = [ ... ];
changeDesc ( 'jquery-ui', 'new description' );
UPDATE:
To get it faster:
var projects = {
jqueryUi : {
value: 'lol1',
desc: 'lol2'
}
};
projects.jqueryUi.desc = 'new string';
(In according to Frédéric's comment you shouldn't use hyphen in the object key, or you should use "jquery-ui" and projects["jquery-ui"] notation.)